1 // Formatting library for C++
2 //
3 // Copyright (c) 2012 - 2016, Victor Zverovich
4 // All rights reserved.
5 //
6 // For the license information refer to format.h.
7
8 #ifndef FMT_FORMAT_INL_H_
9 #define FMT_FORMAT_INL_H_
10
11 #include "format.h"
12
13 #include <string.h>
14
15 #include <cctype>
16 #include <cerrno>
17 #include <climits>
18 #include <cmath>
19 #include <cstdarg>
20 #include <cstddef> // for std::ptrdiff_t
21 #include <cstring> // for std::memmove
22 #include <cwchar>
23 #if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
24 # include <locale>
25 #endif
26
27 #if FMT_USE_WINDOWS_H
28 # if !defined(FMT_HEADER_ONLY) && !defined(WIN32_LEAN_AND_MEAN)
29 # define WIN32_LEAN_AND_MEAN
30 # endif
31 # if defined(NOMINMAX) || defined(FMT_WIN_MINMAX)
32 # include <windows.h>
33 # else
34 # define NOMINMAX
35 # include <windows.h>
36 # undef NOMINMAX
37 # endif
38 #endif
39
40 #if FMT_EXCEPTIONS
41 # define FMT_TRY try
42 # define FMT_CATCH(x) catch (x)
43 #else
44 # define FMT_TRY if (true)
45 # define FMT_CATCH(x) if (false)
46 #endif
47
48 #ifdef _MSC_VER
49 # pragma warning(push)
50 # pragma warning(disable : 4127) // conditional expression is constant
51 # pragma warning(disable : 4702) // unreachable code
52 // Disable deprecation warning for strerror. The latter is not called but
53 // MSVC fails to detect it.
54 # pragma warning(disable : 4996)
55 #endif
56
57 // Dummy implementations of strerror_r and strerror_s called if corresponding
58 // system functions are not available.
strerror_r(int,char *,...)59 inline fmt::internal::null<> strerror_r(int, char*, ...) {
60 return fmt::internal::null<>();
61 }
strerror_s(char *,std::size_t,...)62 inline fmt::internal::null<> strerror_s(char*, std::size_t, ...) {
63 return fmt::internal::null<>();
64 }
65
66 FMT_BEGIN_NAMESPACE
67 namespace internal {
68
69 #ifndef _MSC_VER
70 # define FMT_SNPRINTF snprintf
71 #else // _MSC_VER
72 inline int fmt_snprintf(char* buffer, size_t size, const char* format, ...) {
73 va_list args;
74 va_start(args, format);
75 int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args);
76 va_end(args);
77 return result;
78 }
79 # define FMT_SNPRINTF fmt_snprintf
80 #endif // _MSC_VER
81
82 using format_func = void (*)(internal::buffer<char>&, int, string_view);
83
84 // Portable thread-safe version of strerror.
85 // Sets buffer to point to a string describing the error code.
86 // This can be either a pointer to a string stored in buffer,
87 // or a pointer to some static immutable string.
88 // Returns one of the following values:
89 // 0 - success
90 // ERANGE - buffer is not large enough to store the error message
91 // other - failure
92 // Buffer should be at least of size 1.
safe_strerror(int error_code,char * & buffer,std::size_t buffer_size)93 FMT_FUNC int safe_strerror(int error_code, char*& buffer,
94 std::size_t buffer_size) FMT_NOEXCEPT {
95 FMT_ASSERT(buffer != nullptr && buffer_size != 0, "invalid buffer");
96
97 class dispatcher {
98 private:
99 int error_code_;
100 char*& buffer_;
101 std::size_t buffer_size_;
102
103 // A noop assignment operator to avoid bogus warnings.
104 void operator=(const dispatcher&) {}
105
106 // Handle the result of XSI-compliant version of strerror_r.
107 int handle(int result) {
108 // glibc versions before 2.13 return result in errno.
109 return result == -1 ? errno : result;
110 }
111
112 // Handle the result of GNU-specific version of strerror_r.
113 int handle(char* message) {
114 // If the buffer is full then the message is probably truncated.
115 if (message == buffer_ && strlen(buffer_) == buffer_size_ - 1)
116 return ERANGE;
117 buffer_ = message;
118 return 0;
119 }
120
121 // Handle the case when strerror_r is not available.
122 int handle(internal::null<>) {
123 return fallback(strerror_s(buffer_, buffer_size_, error_code_));
124 }
125
126 // Fallback to strerror_s when strerror_r is not available.
127 int fallback(int result) {
128 // If the buffer is full then the message is probably truncated.
129 return result == 0 && strlen(buffer_) == buffer_size_ - 1 ? ERANGE
130 : result;
131 }
132
133 #if !FMT_MSC_VER
134 // Fallback to strerror if strerror_r and strerror_s are not available.
135 int fallback(internal::null<>) {
136 errno = 0;
137 buffer_ = strerror(error_code_);
138 return errno;
139 }
140 #endif
141
142 public:
143 dispatcher(int err_code, char*& buf, std::size_t buf_size)
144 : error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {}
145
146 int run() { return handle(strerror_r(error_code_, buffer_, buffer_size_)); }
147 };
148 return dispatcher(error_code, buffer, buffer_size).run();
149 }
150
format_error_code(internal::buffer<char> & out,int error_code,string_view message)151 FMT_FUNC void format_error_code(internal::buffer<char>& out, int error_code,
152 string_view message) FMT_NOEXCEPT {
153 // Report error code making sure that the output fits into
154 // inline_buffer_size to avoid dynamic memory allocation and potential
155 // bad_alloc.
156 out.resize(0);
157 static const char SEP[] = ": ";
158 static const char ERROR_STR[] = "error ";
159 // Subtract 2 to account for terminating null characters in SEP and ERROR_STR.
160 std::size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2;
161 auto abs_value = static_cast<uint32_or_64_t<int>>(error_code);
162 if (internal::is_negative(error_code)) {
163 abs_value = 0 - abs_value;
164 ++error_code_size;
165 }
166 error_code_size += internal::to_unsigned(internal::count_digits(abs_value));
167 internal::writer w(out);
168 if (message.size() <= inline_buffer_size - error_code_size) {
169 w.write(message);
170 w.write(SEP);
171 }
172 w.write(ERROR_STR);
173 w.write(error_code);
174 assert(out.size() <= inline_buffer_size);
175 }
176
177 // A wrapper around fwrite that throws on error.
fwrite_fully(const void * ptr,size_t size,size_t count,FILE * stream)178 FMT_FUNC void fwrite_fully(const void* ptr, size_t size, size_t count,
179 FILE* stream) {
180 size_t written = std::fwrite(ptr, size, count, stream);
181 if (written < count) {
182 FMT_THROW(system_error(errno, "cannot write to file"));
183 }
184 }
185
report_error(format_func func,int error_code,string_view message)186 FMT_FUNC void report_error(format_func func, int error_code,
187 string_view message) FMT_NOEXCEPT {
188 memory_buffer full_message;
189 func(full_message, error_code, message);
190 // Don't use fwrite_fully because the latter may throw.
191 (void)std::fwrite(full_message.data(), full_message.size(), 1, stderr);
192 std::fputc('\n', stderr);
193 }
194 } // namespace internal
195
196 #if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
197 namespace internal {
198
199 template <typename Locale>
locale_ref(const Locale & loc)200 locale_ref::locale_ref(const Locale& loc) : locale_(&loc) {
201 static_assert(std::is_same<Locale, std::locale>::value, "");
202 }
203
get()204 template <typename Locale> Locale locale_ref::get() const {
205 static_assert(std::is_same<Locale, std::locale>::value, "");
206 return locale_ ? *static_cast<const std::locale*>(locale_) : std::locale();
207 }
208
thousands_sep_impl(locale_ref loc)209 template <typename Char> FMT_FUNC Char thousands_sep_impl(locale_ref loc) {
210 return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>())
211 .thousands_sep();
212 }
decimal_point_impl(locale_ref loc)213 template <typename Char> FMT_FUNC Char decimal_point_impl(locale_ref loc) {
214 return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>())
215 .decimal_point();
216 }
217 } // namespace internal
218 #else
219 template <typename Char>
thousands_sep_impl(locale_ref)220 FMT_FUNC Char internal::thousands_sep_impl(locale_ref) {
221 return FMT_STATIC_THOUSANDS_SEPARATOR;
222 }
223 template <typename Char>
decimal_point_impl(locale_ref)224 FMT_FUNC Char internal::decimal_point_impl(locale_ref) {
225 return '.';
226 }
227 #endif
228
~format_error()229 FMT_API FMT_FUNC format_error::~format_error() FMT_NOEXCEPT {}
~system_error()230 FMT_API FMT_FUNC system_error::~system_error() FMT_NOEXCEPT {}
231
init(int err_code,string_view format_str,format_args args)232 FMT_FUNC void system_error::init(int err_code, string_view format_str,
233 format_args args) {
234 error_code_ = err_code;
235 memory_buffer buffer;
236 format_system_error(buffer, err_code, vformat(format_str, args));
237 std::runtime_error& base = *this;
238 base = std::runtime_error(to_string(buffer));
239 }
240
241 namespace internal {
242
243 template <> FMT_FUNC int count_digits<4>(internal::fallback_uintptr n) {
244 // Assume little endian; pointer formatting is implementation-defined anyway.
245 int i = static_cast<int>(sizeof(void*)) - 1;
246 while (i > 0 && n.value[i] == 0) --i;
247 auto char_digits = std::numeric_limits<unsigned char>::digits / 4;
248 return i >= 0 ? i * char_digits + count_digits<4, unsigned>(n.value[i]) : 1;
249 }
250
251 template <typename T>
format_float(char * buf,std::size_t size,const char * format,int precision,T value)252 int format_float(char* buf, std::size_t size, const char* format, int precision,
253 T value) {
254 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
255 if (precision > 100000)
256 throw std::runtime_error(
257 "fuzz mode - avoid large allocation inside snprintf");
258 #endif
259 // Suppress the warning about nonliteral format string.
260 auto snprintf_ptr = FMT_SNPRINTF;
261 return precision < 0 ? snprintf_ptr(buf, size, format, value)
262 : snprintf_ptr(buf, size, format, precision, value);
263 }
264
265 template <typename T>
266 const char basic_data<T>::digits[] =
267 "0001020304050607080910111213141516171819"
268 "2021222324252627282930313233343536373839"
269 "4041424344454647484950515253545556575859"
270 "6061626364656667686970717273747576777879"
271 "8081828384858687888990919293949596979899";
272
273 template <typename T>
274 const char basic_data<T>::hex_digits[] = "0123456789abcdef";
275
276 #define FMT_POWERS_OF_10(factor) \
277 factor * 10, factor * 100, factor * 1000, factor * 10000, factor * 100000, \
278 factor * 1000000, factor * 10000000, factor * 100000000, \
279 factor * 1000000000
280
281 template <typename T>
282 const uint64_t basic_data<T>::powers_of_10_64[] = {
283 1, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ull),
284 10000000000000000000ull};
285
286 template <typename T>
287 const uint32_t basic_data<T>::zero_or_powers_of_10_32[] = {0,
288 FMT_POWERS_OF_10(1)};
289
290 template <typename T>
291 const uint64_t basic_data<T>::zero_or_powers_of_10_64[] = {
292 0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ull),
293 10000000000000000000ull};
294
295 // Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340.
296 // These are generated by support/compute-powers.py.
297 template <typename T>
298 const uint64_t basic_data<T>::pow10_significands[] = {
299 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76,
300 0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df,
301 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c,
302 0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5,
303 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57,
304 0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7,
305 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e,
306 0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996,
307 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126,
308 0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053,
309 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f,
310 0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b,
311 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06,
312 0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb,
313 0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000,
314 0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984,
315 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068,
316 0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8,
317 0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758,
318 0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85,
319 0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d,
320 0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25,
321 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2,
322 0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a,
323 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410,
324 0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129,
325 0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85,
326 0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841,
327 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b,
328 };
329
330 // Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding
331 // to significands above.
332 template <typename T>
333 const int16_t basic_data<T>::pow10_exponents[] = {
334 -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954,
335 -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661,
336 -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369,
337 -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77,
338 -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216,
339 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508,
340 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800,
341 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066};
342
343 template <typename T>
344 const char basic_data<T>::foreground_color[] = "\x1b[38;2;";
345 template <typename T>
346 const char basic_data<T>::background_color[] = "\x1b[48;2;";
347 template <typename T> const char basic_data<T>::reset_color[] = "\x1b[0m";
348 template <typename T> const wchar_t basic_data<T>::wreset_color[] = L"\x1b[0m";
349
350 template <typename T> struct bits {
351 static FMT_CONSTEXPR_DECL const int value =
352 static_cast<int>(sizeof(T) * std::numeric_limits<unsigned char>::digits);
353 };
354
355 // A handmade floating-point number f * pow(2, e).
356 class fp {
357 private:
358 using significand_type = uint64_t;
359
360 // All sizes are in bits.
361 // Subtract 1 to account for an implicit most significant bit in the
362 // normalized form.
363 static FMT_CONSTEXPR_DECL const int double_significand_size =
364 std::numeric_limits<double>::digits - 1;
365 static FMT_CONSTEXPR_DECL const uint64_t implicit_bit =
366 1ull << double_significand_size;
367
368 public:
369 significand_type f;
370 int e;
371
372 static FMT_CONSTEXPR_DECL const int significand_size =
373 bits<significand_type>::value;
374
fp()375 fp() : f(0), e(0) {}
fp(uint64_t f_val,int e_val)376 fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {}
377
378 // Constructs fp from an IEEE754 double. It is a template to prevent compile
379 // errors on platforms where double is not IEEE754.
fp(Double d)380 template <typename Double> explicit fp(Double d) {
381 // Assume double is in the format [sign][exponent][significand].
382 using limits = std::numeric_limits<Double>;
383 const int exponent_size =
384 bits<Double>::value - double_significand_size - 1; // -1 for sign
385 const uint64_t significand_mask = implicit_bit - 1;
386 const uint64_t exponent_mask = (~0ull >> 1) & ~significand_mask;
387 const int exponent_bias = (1 << exponent_size) - limits::max_exponent - 1;
388 auto u = bit_cast<uint64_t>(d);
389 auto biased_e = (u & exponent_mask) >> double_significand_size;
390 f = u & significand_mask;
391 if (biased_e != 0)
392 f += implicit_bit;
393 else
394 biased_e = 1; // Subnormals use biased exponent 1 (min exponent).
395 e = static_cast<int>(biased_e - exponent_bias - double_significand_size);
396 }
397
398 // Normalizes the value converted from double and multiplied by (1 << SHIFT).
normalize()399 template <int SHIFT = 0> void normalize() {
400 // Handle subnormals.
401 auto shifted_implicit_bit = implicit_bit << SHIFT;
402 while ((f & shifted_implicit_bit) == 0) {
403 f <<= 1;
404 --e;
405 }
406 // Subtract 1 to account for hidden bit.
407 auto offset = significand_size - double_significand_size - SHIFT - 1;
408 f <<= offset;
409 e -= offset;
410 }
411
412 // Compute lower and upper boundaries (m^- and m^+ in the Grisu paper), where
413 // a boundary is a value half way between the number and its predecessor
414 // (lower) or successor (upper). The upper boundary is normalized and lower
415 // has the same exponent but may be not normalized.
compute_boundaries(fp & lower,fp & upper)416 void compute_boundaries(fp& lower, fp& upper) const {
417 lower =
418 f == implicit_bit ? fp((f << 2) - 1, e - 2) : fp((f << 1) - 1, e - 1);
419 upper = fp((f << 1) + 1, e - 1);
420 upper.normalize<1>(); // 1 is to account for the exponent shift above.
421 lower.f <<= lower.e - upper.e;
422 lower.e = upper.e;
423 }
424 };
425
426 // Returns an fp number representing x - y. Result may not be normalized.
427 inline fp operator-(fp x, fp y) {
428 FMT_ASSERT(x.f >= y.f && x.e == y.e, "invalid operands");
429 return fp(x.f - y.f, x.e);
430 }
431
432 // Computes an fp number r with r.f = x.f * y.f / pow(2, 64) rounded to nearest
433 // with half-up tie breaking, r.e = x.e + y.e + 64. Result may not be
434 // normalized.
435 FMT_FUNC fp operator*(fp x, fp y) {
436 int exp = x.e + y.e + 64;
437 #if FMT_USE_INT128
438 auto product = static_cast<__uint128_t>(x.f) * y.f;
439 auto f = static_cast<uint64_t>(product >> 64);
440 if ((static_cast<uint64_t>(product) & (1ULL << 63)) != 0) ++f;
441 return fp(f, exp);
442 #else
443 // Multiply 32-bit parts of significands.
444 uint64_t mask = (1ULL << 32) - 1;
445 uint64_t a = x.f >> 32, b = x.f & mask;
446 uint64_t c = y.f >> 32, d = y.f & mask;
447 uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d;
448 // Compute mid 64-bit of result and round.
449 uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31);
450 return fp(ac + (ad >> 32) + (bc >> 32) + (mid >> 32), exp);
451 #endif
452 }
453
454 // Returns cached power (of 10) c_k = c_k.f * pow(2, c_k.e) such that its
455 // (binary) exponent satisfies min_exponent <= c_k.e <= min_exponent + 28.
get_cached_power(int min_exponent,int & pow10_exponent)456 FMT_FUNC fp get_cached_power(int min_exponent, int& pow10_exponent) {
457 const double one_over_log2_10 = 0.30102999566398114; // 1 / log2(10)
458 int index = static_cast<int>(
459 std::ceil((min_exponent + fp::significand_size - 1) * one_over_log2_10));
460 // Decimal exponent of the first (smallest) cached power of 10.
461 const int first_dec_exp = -348;
462 // Difference between 2 consecutive decimal exponents in cached powers of 10.
463 const int dec_exp_step = 8;
464 index = (index - first_dec_exp - 1) / dec_exp_step + 1;
465 pow10_exponent = first_dec_exp + index * dec_exp_step;
466 return fp(data::pow10_significands[index], data::pow10_exponents[index]);
467 }
468
469 enum round_direction { unknown, up, down };
470
471 // Given the divisor (normally a power of 10), the remainder = v % divisor for
472 // some number v and the error, returns whether v should be rounded up, down, or
473 // whether the rounding direction can't be determined due to error.
474 // error should be less than divisor / 2.
get_round_direction(uint64_t divisor,uint64_t remainder,uint64_t error)475 inline round_direction get_round_direction(uint64_t divisor, uint64_t remainder,
476 uint64_t error) {
477 FMT_ASSERT(remainder < divisor, ""); // divisor - remainder won't overflow.
478 FMT_ASSERT(error < divisor, ""); // divisor - error won't overflow.
479 FMT_ASSERT(error < divisor - error, ""); // error * 2 won't overflow.
480 // Round down if (remainder + error) * 2 <= divisor.
481 if (remainder <= divisor - remainder && error * 2 <= divisor - remainder * 2)
482 return down;
483 // Round up if (remainder - error) * 2 >= divisor.
484 if (remainder >= error &&
485 remainder - error >= divisor - (remainder - error)) {
486 return up;
487 }
488 return unknown;
489 }
490
491 namespace digits {
492 enum result {
493 more, // Generate more digits.
494 done, // Done generating digits.
495 error // Digit generation cancelled due to an error.
496 };
497 }
498
499 // Generates output using the Grisu digit-gen algorithm.
500 // error: the size of the region (lower, upper) outside of which numbers
501 // definitely do not round to value (Delta in Grisu3).
502 template <typename Handler>
grisu_gen_digits(fp value,uint64_t error,int & exp,Handler & handler)503 digits::result grisu_gen_digits(fp value, uint64_t error, int& exp,
504 Handler& handler) {
505 fp one(1ull << -value.e, value.e);
506 // The integral part of scaled value (p1 in Grisu) = value / one. It cannot be
507 // zero because it contains a product of two 64-bit numbers with MSB set (due
508 // to normalization) - 1, shifted right by at most 60 bits.
509 uint32_t integral = static_cast<uint32_t>(value.f >> -one.e);
510 FMT_ASSERT(integral != 0, "");
511 FMT_ASSERT(integral == value.f >> -one.e, "");
512 // The fractional part of scaled value (p2 in Grisu) c = value % one.
513 uint64_t fractional = value.f & (one.f - 1);
514 exp = count_digits(integral); // kappa in Grisu.
515 // Divide by 10 to prevent overflow.
516 auto result = handler.on_start(data::powers_of_10_64[exp - 1] << -one.e,
517 value.f / 10, error * 10, exp);
518 if (result != digits::more) return result;
519 // Generate digits for the integral part. This can produce up to 10 digits.
520 do {
521 uint32_t digit = 0;
522 // This optimization by miloyip reduces the number of integer divisions by
523 // one per iteration.
524 switch (exp) {
525 case 10:
526 digit = integral / 1000000000;
527 integral %= 1000000000;
528 break;
529 case 9:
530 digit = integral / 100000000;
531 integral %= 100000000;
532 break;
533 case 8:
534 digit = integral / 10000000;
535 integral %= 10000000;
536 break;
537 case 7:
538 digit = integral / 1000000;
539 integral %= 1000000;
540 break;
541 case 6:
542 digit = integral / 100000;
543 integral %= 100000;
544 break;
545 case 5:
546 digit = integral / 10000;
547 integral %= 10000;
548 break;
549 case 4:
550 digit = integral / 1000;
551 integral %= 1000;
552 break;
553 case 3:
554 digit = integral / 100;
555 integral %= 100;
556 break;
557 case 2:
558 digit = integral / 10;
559 integral %= 10;
560 break;
561 case 1:
562 digit = integral;
563 integral = 0;
564 break;
565 default:
566 FMT_ASSERT(false, "invalid number of digits");
567 }
568 --exp;
569 uint64_t remainder =
570 (static_cast<uint64_t>(integral) << -one.e) + fractional;
571 result = handler.on_digit(static_cast<char>('0' + digit),
572 data::powers_of_10_64[exp] << -one.e, remainder,
573 error, exp, true);
574 if (result != digits::more) return result;
575 } while (exp > 0);
576 // Generate digits for the fractional part.
577 for (;;) {
578 fractional *= 10;
579 error *= 10;
580 char digit =
581 static_cast<char>('0' + static_cast<char>(fractional >> -one.e));
582 fractional &= one.f - 1;
583 --exp;
584 result = handler.on_digit(digit, one.f, fractional, error, exp, false);
585 if (result != digits::more) return result;
586 }
587 }
588
589 // The fixed precision digit handler.
590 struct fixed_handler {
591 char* buf;
592 int size;
593 int precision;
594 int exp10;
595 bool fixed;
596
on_startfixed_handler597 digits::result on_start(uint64_t divisor, uint64_t remainder, uint64_t error,
598 int& exp) {
599 // Non-fixed formats require at least one digit and no precision adjustment.
600 if (!fixed) return digits::more;
601 // Adjust fixed precision by exponent because it is relative to decimal
602 // point.
603 precision += exp + exp10;
604 // Check if precision is satisfied just by leading zeros, e.g.
605 // format("{:.2f}", 0.001) gives "0.00" without generating any digits.
606 if (precision > 0) return digits::more;
607 if (precision < 0) return digits::done;
608 auto dir = get_round_direction(divisor, remainder, error);
609 if (dir == unknown) return digits::error;
610 buf[size++] = dir == up ? '1' : '0';
611 return digits::done;
612 }
613
on_digitfixed_handler614 digits::result on_digit(char digit, uint64_t divisor, uint64_t remainder,
615 uint64_t error, int, bool integral) {
616 FMT_ASSERT(remainder < divisor, "");
617 buf[size++] = digit;
618 if (size < precision) return digits::more;
619 if (!integral) {
620 // Check if error * 2 < divisor with overflow prevention.
621 // The check is not needed for the integral part because error = 1
622 // and divisor > (1 << 32) there.
623 if (error >= divisor || error >= divisor - error) return digits::error;
624 } else {
625 FMT_ASSERT(error == 1 && divisor > 2, "");
626 }
627 auto dir = get_round_direction(divisor, remainder, error);
628 if (dir != up) return dir == down ? digits::done : digits::error;
629 ++buf[size - 1];
630 for (int i = size - 1; i > 0 && buf[i] > '9'; --i) {
631 buf[i] = '0';
632 ++buf[i - 1];
633 }
634 if (buf[0] > '9') {
635 buf[0] = '1';
636 buf[size++] = '0';
637 }
638 return digits::done;
639 }
640 };
641
642 // The shortest representation digit handler.
643 template <int GRISU_VERSION> struct grisu_shortest_handler {
644 char* buf;
645 int size;
646 // Distance between scaled value and upper bound (wp_W in Grisu3).
647 uint64_t diff;
648
on_startgrisu_shortest_handler649 digits::result on_start(uint64_t, uint64_t, uint64_t, int&) {
650 return digits::more;
651 }
652
653 // Decrement the generated number approaching value from above.
roundgrisu_shortest_handler654 void round(uint64_t d, uint64_t divisor, uint64_t& remainder,
655 uint64_t error) {
656 while (
657 remainder < d && error - remainder >= divisor &&
658 (remainder + divisor < d || d - remainder >= remainder + divisor - d)) {
659 --buf[size - 1];
660 remainder += divisor;
661 }
662 }
663
664 // Implements Grisu's round_weed.
on_digitgrisu_shortest_handler665 digits::result on_digit(char digit, uint64_t divisor, uint64_t remainder,
666 uint64_t error, int exp, bool integral) {
667 buf[size++] = digit;
668 if (remainder >= error) return digits::more;
669 if (GRISU_VERSION != 3) {
670 uint64_t d = integral ? diff : diff * data::powers_of_10_64[-exp];
671 round(d, divisor, remainder, error);
672 return digits::done;
673 }
674 uint64_t unit = integral ? 1 : data::powers_of_10_64[-exp];
675 uint64_t up = (diff - 1) * unit; // wp_Wup
676 round(up, divisor, remainder, error);
677 uint64_t down = (diff + 1) * unit; // wp_Wdown
678 if (remainder < down && error - remainder >= divisor &&
679 (remainder + divisor < down ||
680 down - remainder > remainder + divisor - down)) {
681 return digits::error;
682 }
683 return 2 * unit <= remainder && remainder <= error - 4 * unit
684 ? digits::done
685 : digits::error;
686 }
687 };
688
689 template <typename Double,
690 enable_if_t<(sizeof(Double) == sizeof(uint64_t)), int>>
grisu_format(Double value,buffer<char> & buf,int precision,unsigned options,int & exp)691 FMT_API bool grisu_format(Double value, buffer<char>& buf, int precision,
692 unsigned options, int& exp) {
693 FMT_ASSERT(value >= 0, "value is negative");
694 bool fixed = (options & grisu_options::fixed) != 0;
695 if (value <= 0) { // <= instead of == to silence a warning.
696 if (precision <= 0 || !fixed) {
697 exp = 0;
698 buf.push_back('0');
699 } else {
700 exp = -precision;
701 buf.resize(precision);
702 std::uninitialized_fill_n(buf.data(), precision, '0');
703 }
704 return true;
705 }
706
707 fp fp_value(value);
708 const int min_exp = -60; // alpha in Grisu.
709 int cached_exp10 = 0; // K in Grisu.
710 if (precision != -1) {
711 if (precision > 17) return false;
712 fp_value.normalize();
713 auto cached_pow = get_cached_power(
714 min_exp - (fp_value.e + fp::significand_size), cached_exp10);
715 fp_value = fp_value * cached_pow;
716 fixed_handler handler{buf.data(), 0, precision, -cached_exp10, fixed};
717 if (grisu_gen_digits(fp_value, 1, exp, handler) == digits::error)
718 return false;
719 buf.resize(to_unsigned(handler.size));
720 } else {
721 fp lower, upper; // w^- and w^+ in the Grisu paper.
722 fp_value.compute_boundaries(lower, upper);
723 // Find a cached power of 10 such that multiplying upper by it will bring
724 // the exponent in the range [min_exp, -32].
725 auto cached_pow = get_cached_power( // \tilde{c}_{-k} in Grisu.
726 min_exp - (upper.e + fp::significand_size), cached_exp10);
727 fp_value.normalize();
728 fp_value = fp_value * cached_pow;
729 lower = lower * cached_pow; // \tilde{M}^- in Grisu.
730 upper = upper * cached_pow; // \tilde{M}^+ in Grisu.
731 assert(min_exp <= upper.e && upper.e <= -32);
732 auto result = digits::result();
733 int size = 0;
734 if ((options & grisu_options::grisu3) != 0) {
735 --lower.f; // \tilde{M}^- - 1 ulp -> M^-_{\downarrow}.
736 ++upper.f; // \tilde{M}^+ + 1 ulp -> M^+_{\uparrow}.
737 // Numbers outside of (lower, upper) definitely do not round to value.
738 grisu_shortest_handler<3> handler{buf.data(), 0, (upper - fp_value).f};
739 result = grisu_gen_digits(upper, upper.f - lower.f, exp, handler);
740 size = handler.size;
741 } else {
742 ++lower.f; // \tilde{M}^- + 1 ulp -> M^-_{\uparrow}.
743 --upper.f; // \tilde{M}^+ - 1 ulp -> M^+_{\downarrow}.
744 grisu_shortest_handler<2> handler{buf.data(), 0, (upper - fp_value).f};
745 result = grisu_gen_digits(upper, upper.f - lower.f, exp, handler);
746 size = handler.size;
747 }
748 if (result == digits::error) return false;
749 buf.resize(to_unsigned(size));
750 }
751 exp -= cached_exp10;
752 return true;
753 }
754
755 template <typename Double>
sprintf_format(Double value,internal::buffer<char> & buf,sprintf_specs specs)756 char* sprintf_format(Double value, internal::buffer<char>& buf,
757 sprintf_specs specs) {
758 // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail.
759 FMT_ASSERT(buf.capacity() != 0, "empty buffer");
760
761 // Build format string.
762 enum { max_format_size = 10 }; // longest format: %#-*.*Lg
763 char format[max_format_size];
764 char* format_ptr = format;
765 *format_ptr++ = '%';
766 if (specs.alt || !specs.type) *format_ptr++ = '#';
767 if (specs.precision >= 0) {
768 *format_ptr++ = '.';
769 *format_ptr++ = '*';
770 }
771 if (std::is_same<Double, long double>::value) *format_ptr++ = 'L';
772
773 char type = specs.type;
774
775 if (type == '%')
776 type = 'f';
777 else if (type == 0 || type == 'n')
778 type = 'g';
779 #if FMT_MSC_VER
780 if (type == 'F') {
781 // MSVC's printf doesn't support 'F'.
782 type = 'f';
783 }
784 #endif
785 *format_ptr++ = type;
786 *format_ptr = '\0';
787
788 // Format using snprintf.
789 char* start = nullptr;
790 char* decimal_point_pos = nullptr;
791 for (;;) {
792 std::size_t buffer_size = buf.capacity();
793 start = &buf[0];
794 int result =
795 format_float(start, buffer_size, format, specs.precision, value);
796 if (result >= 0) {
797 unsigned n = internal::to_unsigned(result);
798 if (n < buf.capacity()) {
799 // Find the decimal point.
800 auto p = buf.data(), end = p + n;
801 if (*p == '+' || *p == '-') ++p;
802 if (specs.type != 'a' && specs.type != 'A') {
803 while (p < end && *p >= '0' && *p <= '9') ++p;
804 if (p < end && *p != 'e' && *p != 'E') {
805 decimal_point_pos = p;
806 if (!specs.type) {
807 // Keep only one trailing zero after the decimal point.
808 ++p;
809 if (*p == '0') ++p;
810 while (p != end && *p >= '1' && *p <= '9') ++p;
811 char* where = p;
812 while (p != end && *p == '0') ++p;
813 if (p == end || *p < '0' || *p > '9') {
814 if (p != end) std::memmove(where, p, to_unsigned(end - p));
815 n -= static_cast<unsigned>(p - where);
816 }
817 }
818 }
819 }
820 buf.resize(n);
821 break; // The buffer is large enough - continue with formatting.
822 }
823 buf.reserve(n + 1);
824 } else {
825 // If result is negative we ask to increase the capacity by at least 1,
826 // but as std::vector, the buffer grows exponentially.
827 buf.reserve(buf.capacity() + 1);
828 }
829 }
830 return decimal_point_pos;
831 }
832 } // namespace internal
833
834 #if FMT_USE_WINDOWS_H
835
utf8_to_utf16(string_view s)836 FMT_FUNC internal::utf8_to_utf16::utf8_to_utf16(string_view s) {
837 static const char ERROR_MSG[] = "cannot convert string from UTF-8 to UTF-16";
838 if (s.size() > INT_MAX)
839 FMT_THROW(windows_error(ERROR_INVALID_PARAMETER, ERROR_MSG));
840 int s_size = static_cast<int>(s.size());
841 if (s_size == 0) {
842 // MultiByteToWideChar does not support zero length, handle separately.
843 buffer_.resize(1);
844 buffer_[0] = 0;
845 return;
846 }
847
848 int length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(),
849 s_size, nullptr, 0);
850 if (length == 0) FMT_THROW(windows_error(GetLastError(), ERROR_MSG));
851 buffer_.resize(length + 1);
852 length = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s.data(), s_size,
853 &buffer_[0], length);
854 if (length == 0) FMT_THROW(windows_error(GetLastError(), ERROR_MSG));
855 buffer_[length] = 0;
856 }
857
utf16_to_utf8(wstring_view s)858 FMT_FUNC internal::utf16_to_utf8::utf16_to_utf8(wstring_view s) {
859 if (int error_code = convert(s)) {
860 FMT_THROW(windows_error(error_code,
861 "cannot convert string from UTF-16 to UTF-8"));
862 }
863 }
864
convert(wstring_view s)865 FMT_FUNC int internal::utf16_to_utf8::convert(wstring_view s) {
866 if (s.size() > INT_MAX) return ERROR_INVALID_PARAMETER;
867 int s_size = static_cast<int>(s.size());
868 if (s_size == 0) {
869 // WideCharToMultiByte does not support zero length, handle separately.
870 buffer_.resize(1);
871 buffer_[0] = 0;
872 return 0;
873 }
874
875 int length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, nullptr, 0,
876 nullptr, nullptr);
877 if (length == 0) return GetLastError();
878 buffer_.resize(length + 1);
879 length = WideCharToMultiByte(CP_UTF8, 0, s.data(), s_size, &buffer_[0],
880 length, nullptr, nullptr);
881 if (length == 0) return GetLastError();
882 buffer_[length] = 0;
883 return 0;
884 }
885
init(int err_code,string_view format_str,format_args args)886 FMT_FUNC void windows_error::init(int err_code, string_view format_str,
887 format_args args) {
888 error_code_ = err_code;
889 memory_buffer buffer;
890 internal::format_windows_error(buffer, err_code, vformat(format_str, args));
891 std::runtime_error& base = *this;
892 base = std::runtime_error(to_string(buffer));
893 }
894
format_windows_error(internal::buffer<char> & out,int error_code,string_view message)895 FMT_FUNC void internal::format_windows_error(internal::buffer<char>& out,
896 int error_code,
897 string_view message) FMT_NOEXCEPT {
898 FMT_TRY {
899 wmemory_buffer buf;
900 buf.resize(inline_buffer_size);
901 for (;;) {
902 wchar_t* system_message = &buf[0];
903 int result = FormatMessageW(
904 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
905 error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), system_message,
906 static_cast<uint32_t>(buf.size()), nullptr);
907 if (result != 0) {
908 utf16_to_utf8 utf8_message;
909 if (utf8_message.convert(system_message) == ERROR_SUCCESS) {
910 internal::writer w(out);
911 w.write(message);
912 w.write(": ");
913 w.write(utf8_message);
914 return;
915 }
916 break;
917 }
918 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
919 break; // Can't get error message, report error code instead.
920 buf.resize(buf.size() * 2);
921 }
922 }
923 FMT_CATCH(...) {}
924 format_error_code(out, error_code, message);
925 }
926
927 #endif // FMT_USE_WINDOWS_H
928
format_system_error(internal::buffer<char> & out,int error_code,string_view message)929 FMT_FUNC void format_system_error(internal::buffer<char>& out, int error_code,
930 string_view message) FMT_NOEXCEPT {
931 FMT_TRY {
932 memory_buffer buf;
933 buf.resize(inline_buffer_size);
934 for (;;) {
935 char* system_message = &buf[0];
936 int result =
937 internal::safe_strerror(error_code, system_message, buf.size());
938 if (result == 0) {
939 internal::writer w(out);
940 w.write(message);
941 w.write(": ");
942 w.write(system_message);
943 return;
944 }
945 if (result != ERANGE)
946 break; // Can't get error message, report error code instead.
947 buf.resize(buf.size() * 2);
948 }
949 }
950 FMT_CATCH(...) {}
951 format_error_code(out, error_code, message);
952 }
953
on_error(const char * message)954 FMT_FUNC void internal::error_handler::on_error(const char* message) {
955 FMT_THROW(format_error(message));
956 }
957
report_system_error(int error_code,fmt::string_view message)958 FMT_FUNC void report_system_error(int error_code,
959 fmt::string_view message) FMT_NOEXCEPT {
960 report_error(format_system_error, error_code, message);
961 }
962
963 #if FMT_USE_WINDOWS_H
report_windows_error(int error_code,fmt::string_view message)964 FMT_FUNC void report_windows_error(int error_code,
965 fmt::string_view message) FMT_NOEXCEPT {
966 report_error(internal::format_windows_error, error_code, message);
967 }
968 #endif
969
vprint(std::FILE * f,string_view format_str,format_args args)970 FMT_FUNC void vprint(std::FILE* f, string_view format_str, format_args args) {
971 memory_buffer buffer;
972 internal::vformat_to(buffer, format_str,
973 basic_format_args<buffer_context<char>>(args));
974 internal::fwrite_fully(buffer.data(), 1, buffer.size(), f);
975 }
976
vprint(std::FILE * f,wstring_view format_str,wformat_args args)977 FMT_FUNC void vprint(std::FILE* f, wstring_view format_str, wformat_args args) {
978 wmemory_buffer buffer;
979 internal::vformat_to(buffer, format_str, args);
980 buffer.push_back(L'\0');
981 if (std::fputws(buffer.data(), f) == -1) {
982 FMT_THROW(system_error(errno, "cannot write to file"));
983 }
984 }
985
vprint(string_view format_str,format_args args)986 FMT_FUNC void vprint(string_view format_str, format_args args) {
987 vprint(stdout, format_str, args);
988 }
989
vprint(wstring_view format_str,wformat_args args)990 FMT_FUNC void vprint(wstring_view format_str, wformat_args args) {
991 vprint(stdout, format_str, args);
992 }
993
994 FMT_END_NAMESPACE
995
996 #ifdef _MSC_VER
997 # pragma warning(pop)
998 #endif
999
1000 #endif // FMT_FORMAT_INL_H_
1001