1 // -*- C++ -*-
2 //===----------------------------------------------------------------------===//
3 //
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef _LIBCPP___FORMAT_FORMATTER_FLOATING_POINT_H
11 #define _LIBCPP___FORMAT_FORMATTER_FLOATING_POINT_H
12
13 #include <__algorithm/copy_n.h>
14 #include <__algorithm/find.h>
15 #include <__algorithm/max.h>
16 #include <__algorithm/min.h>
17 #include <__algorithm/rotate.h>
18 #include <__algorithm/transform.h>
19 #include <__concepts/arithmetic.h>
20 #include <__concepts/same_as.h>
21 #include <__config>
22 #include <__format/concepts.h>
23 #include <__format/format_parse_context.h>
24 #include <__format/formatter.h>
25 #include <__format/formatter_integral.h>
26 #include <__format/formatter_output.h>
27 #include <__format/parser_std_format_spec.h>
28 #include <__memory/allocator.h>
29 #include <__utility/move.h>
30 #include <__utility/unreachable.h>
31 #include <charconv>
32
33 #ifndef _LIBCPP_HAS_NO_LOCALIZATION
34 # include <locale>
35 #endif
36
37 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
38 # pragma GCC system_header
39 #endif
40
41 _LIBCPP_PUSH_MACROS
42 #include <__undef_macros>
43
44 _LIBCPP_BEGIN_NAMESPACE_STD
45
46 #if _LIBCPP_STD_VER > 17
47
48 namespace __formatter {
49
50 template <floating_point _Tp>
__to_buffer(char * __first,char * __last,_Tp __value)51 _LIBCPP_HIDE_FROM_ABI char* __to_buffer(char* __first, char* __last, _Tp __value) {
52 to_chars_result __r = _VSTD::to_chars(__first, __last, __value);
53 _LIBCPP_ASSERT(__r.ec == errc(0), "Internal buffer too small");
54 return __r.ptr;
55 }
56
57 template <floating_point _Tp>
__to_buffer(char * __first,char * __last,_Tp __value,chars_format __fmt)58 _LIBCPP_HIDE_FROM_ABI char* __to_buffer(char* __first, char* __last, _Tp __value, chars_format __fmt) {
59 to_chars_result __r = _VSTD::to_chars(__first, __last, __value, __fmt);
60 _LIBCPP_ASSERT(__r.ec == errc(0), "Internal buffer too small");
61 return __r.ptr;
62 }
63
64 template <floating_point _Tp>
__to_buffer(char * __first,char * __last,_Tp __value,chars_format __fmt,int __precision)65 _LIBCPP_HIDE_FROM_ABI char* __to_buffer(char* __first, char* __last, _Tp __value, chars_format __fmt, int __precision) {
66 to_chars_result __r = _VSTD::to_chars(__first, __last, __value, __fmt, __precision);
67 _LIBCPP_ASSERT(__r.ec == errc(0), "Internal buffer too small");
68 return __r.ptr;
69 }
70
71 // https://en.cppreference.com/w/cpp/language/types#cite_note-1
72 // float min subnormal: +/-0x1p-149 max: +/- 3.402,823,4 10^38
73 // double min subnormal: +/-0x1p-1074 max +/- 1.797,693,134,862,315,7 10^308
74 // long double (x86) min subnormal: +/-0x1p-16446 max: +/- 1.189,731,495,357,231,765,021 10^4932
75 //
76 // The maximum number of digits required for the integral part is based on the
77 // maximum's value power of 10. Every power of 10 requires one additional
78 // decimal digit.
79 // The maximum number of digits required for the fractional part is based on
80 // the minimal subnormal hexadecimal output's power of 10. Every division of a
81 // fraction's binary 1 by 2, requires one additional decimal digit.
82 //
83 // The maximum size of a formatted value depends on the selected output format.
84 // Ignoring the fact the format string can request a precision larger than the
85 // values maximum required, these values are:
86 //
87 // sign 1 code unit
88 // __max_integral
89 // radix point 1 code unit
90 // __max_fractional
91 // exponent character 1 code unit
92 // sign 1 code unit
93 // __max_fractional_value
94 // -----------------------------------
95 // total 4 code units extra required.
96 //
97 // TODO FMT Optimize the storage to avoid storing digits that are known to be zero.
98 // https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/
99
100 // TODO FMT Add long double specialization when to_chars has proper long double support.
101 template <class _Tp>
102 struct __traits;
103
104 template <floating_point _Fp>
__float_buffer_size(int __precision)105 _LIBCPP_HIDE_FROM_ABI constexpr size_t __float_buffer_size(int __precision) {
106 using _Traits = __traits<_Fp>;
107 return 4 + _Traits::__max_integral + __precision + _Traits::__max_fractional_value;
108 }
109
110 template <>
111 struct __traits<float> {
112 static constexpr int __max_integral = 38;
113 static constexpr int __max_fractional = 149;
114 static constexpr int __max_fractional_value = 3;
115 static constexpr size_t __stack_buffer_size = 256;
116
117 static constexpr int __hex_precision_digits = 3;
118 };
119
120 template <>
121 struct __traits<double> {
122 static constexpr int __max_integral = 308;
123 static constexpr int __max_fractional = 1074;
124 static constexpr int __max_fractional_value = 4;
125 static constexpr size_t __stack_buffer_size = 1024;
126
127 static constexpr int __hex_precision_digits = 4;
128 };
129
130 /// Helper class to store the conversion buffer.
131 ///
132 /// Depending on the maxium size required for a value, the buffer is allocated
133 /// on the stack or the heap.
134 template <floating_point _Fp>
135 class _LIBCPP_TEMPLATE_VIS __float_buffer {
136 using _Traits = __traits<_Fp>;
137
138 public:
139 // TODO FMT Improve this constructor to do a better estimate.
140 // When using a scientific formatting with a precision of 6 a stack buffer
141 // will always suffice. At the moment that isn't important since floats and
142 // doubles use a stack buffer, unless the precision used in the format string
143 // is large.
144 // When supporting long doubles the __max_integral part becomes 4932 which
145 // may be too much for some platforms. For these cases a better estimate is
146 // required.
147 explicit _LIBCPP_HIDE_FROM_ABI __float_buffer(int __precision)
148 : __precision_(__precision != -1 ? __precision : _Traits::__max_fractional) {
149
150 // When the precision is larger than _Traits::__max_fractional the digits in
151 // the range (_Traits::__max_fractional, precision] will contain the value
152 // zero. There's no need to request to_chars to write these zeros:
153 // - When the value is large a temporary heap buffer needs to be allocated.
154 // - When to_chars writes the values they need to be "copied" to the output:
155 // - char: std::fill on the output iterator is faster than std::copy.
156 // - wchar_t: same argument as char, but additional std::copy won't work.
157 // The input is always a char buffer, so every char in the buffer needs
158 // to be converted from a char to a wchar_t.
159 if (__precision_ > _Traits::__max_fractional) {
160 __num_trailing_zeros_ = __precision_ - _Traits::__max_fractional;
161 __precision_ = _Traits::__max_fractional;
162 }
163
164 __size_ = __formatter::__float_buffer_size<_Fp>(__precision_);
165 if (__size_ > _Traits::__stack_buffer_size)
166 // The allocated buffer's contents don't need initialization.
167 __begin_ = allocator<char>{}.allocate(__size_);
168 else
169 __begin_ = __buffer_;
170 }
171
172 _LIBCPP_HIDE_FROM_ABI ~__float_buffer() {
173 if (__size_ > _Traits::__stack_buffer_size)
174 allocator<char>{}.deallocate(__begin_, __size_);
175 }
176 _LIBCPP_HIDE_FROM_ABI __float_buffer(const __float_buffer&) = delete;
177 _LIBCPP_HIDE_FROM_ABI __float_buffer& operator=(const __float_buffer&) = delete;
178
179 _LIBCPP_HIDE_FROM_ABI char* begin() const { return __begin_; }
180 _LIBCPP_HIDE_FROM_ABI char* end() const { return __begin_ + __size_; }
181
182 _LIBCPP_HIDE_FROM_ABI int __precision() const { return __precision_; }
183 _LIBCPP_HIDE_FROM_ABI int __num_trailing_zeros() const { return __num_trailing_zeros_; }
184 _LIBCPP_HIDE_FROM_ABI void __remove_trailing_zeros() { __num_trailing_zeros_ = 0; }
185 _LIBCPP_HIDE_FROM_ABI void __add_trailing_zeros(int __zeros) { __num_trailing_zeros_ += __zeros; }
186
187 private:
188 int __precision_;
189 int __num_trailing_zeros_{0};
190 size_t __size_;
191 char* __begin_;
192 char __buffer_[_Traits::__stack_buffer_size];
193 };
194
195 struct __float_result {
196 /// Points at the beginning of the integral part in the buffer.
197 ///
198 /// When there's no sign character this points at the start of the buffer.
199 char* __integral;
200
201 /// Points at the radix point, when not present it's the same as \ref __last.
202 char* __radix_point;
203
204 /// Points at the exponent character, when not present it's the same as \ref __last.
205 char* __exponent;
206
207 /// Points beyond the last written element in the buffer.
208 char* __last;
209 };
210
211 /// Finds the position of the exponent character 'e' at the end of the buffer.
212 ///
213 /// Assuming there is an exponent the input will terminate with
214 /// eSdd and eSdddd (S = sign, d = digit)
215 ///
216 /// \returns a pointer to the exponent or __last when not found.
217 constexpr inline _LIBCPP_HIDE_FROM_ABI char* __find_exponent(char* __first, char* __last) {
218 ptrdiff_t __size = __last - __first;
219 if (__size >= 4) {
220 __first = __last - _VSTD::min(__size, ptrdiff_t(6));
221 for (; __first != __last - 3; ++__first) {
222 if (*__first == 'e')
223 return __first;
224 }
225 }
226 return __last;
227 }
228
229 template <class _Fp, class _Tp>
230 _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_default(const __float_buffer<_Fp>& __buffer, _Tp __value,
231 char* __integral) {
232 __float_result __result;
233 __result.__integral = __integral;
234 __result.__last = __formatter::__to_buffer(__integral, __buffer.end(), __value);
235
236 __result.__exponent = __formatter::__find_exponent(__result.__integral, __result.__last);
237
238 // Constrains:
239 // - There's at least one decimal digit before the radix point.
240 // - The radix point, when present, is placed before the exponent.
241 __result.__radix_point = _VSTD::find(__result.__integral + 1, __result.__exponent, '.');
242
243 // When the radix point isn't found its position is the exponent instead of
244 // __result.__last.
245 if (__result.__radix_point == __result.__exponent)
246 __result.__radix_point = __result.__last;
247
248 // clang-format off
249 _LIBCPP_ASSERT((__result.__integral != __result.__last) &&
250 (__result.__radix_point == __result.__last || *__result.__radix_point == '.') &&
251 (__result.__exponent == __result.__last || *__result.__exponent == 'e'),
252 "Post-condition failure.");
253 // clang-format on
254
255 return __result;
256 }
257
258 template <class _Fp, class _Tp>
259 _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_hexadecimal_lower_case(const __float_buffer<_Fp>& __buffer,
260 _Tp __value, int __precision,
261 char* __integral) {
262 __float_result __result;
263 __result.__integral = __integral;
264 if (__precision == -1)
265 __result.__last = __formatter::__to_buffer(__integral, __buffer.end(), __value, chars_format::hex);
266 else
267 __result.__last = __formatter::__to_buffer(__integral, __buffer.end(), __value, chars_format::hex, __precision);
268
269 // H = one or more hex-digits
270 // S = sign
271 // D = one or more decimal-digits
272 // When the fractional part is zero and no precision the output is 0p+0
273 // else the output is 0.HpSD
274 // So testing the second position can differentiate between these two cases.
275 char* __first = __integral + 1;
276 if (*__first == '.') {
277 __result.__radix_point = __first;
278 // One digit is the minimum
279 // 0.hpSd
280 // ^-- last
281 // ^---- integral = end of search
282 // ^-------- start of search
283 // 0123456
284 //
285 // Four digits is the maximum
286 // 0.hpSdddd
287 // ^-- last
288 // ^---- integral = end of search
289 // ^-------- start of search
290 // 0123456789
291 static_assert(__traits<_Fp>::__hex_precision_digits <= 4, "Guard against possible underflow.");
292
293 char* __last = __result.__last - 2;
294 __first = __last - __traits<_Fp>::__hex_precision_digits;
295 __result.__exponent = _VSTD::find(__first, __last, 'p');
296 } else {
297 __result.__radix_point = __result.__last;
298 __result.__exponent = __first;
299 }
300
301 // clang-format off
302 _LIBCPP_ASSERT((__result.__integral != __result.__last) &&
303 (__result.__radix_point == __result.__last || *__result.__radix_point == '.') &&
304 (__result.__exponent != __result.__last && *__result.__exponent == 'p'),
305 "Post-condition failure.");
306 // clang-format on
307
308 return __result;
309 }
310
311 template <class _Fp, class _Tp>
312 _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_hexadecimal_upper_case(const __float_buffer<_Fp>& __buffer,
313 _Tp __value, int __precision,
314 char* __integral) {
315 __float_result __result =
316 __formatter::__format_buffer_hexadecimal_lower_case(__buffer, __value, __precision, __integral);
317 _VSTD::transform(__result.__integral, __result.__exponent, __result.__integral, __hex_to_upper);
318 *__result.__exponent = 'P';
319 return __result;
320 }
321
322 template <class _Fp, class _Tp>
323 _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_scientific_lower_case(const __float_buffer<_Fp>& __buffer,
324 _Tp __value, int __precision,
325 char* __integral) {
326 __float_result __result;
327 __result.__integral = __integral;
328 __result.__last =
329 __formatter::__to_buffer(__integral, __buffer.end(), __value, chars_format::scientific, __precision);
330
331 char* __first = __integral + 1;
332 _LIBCPP_ASSERT(__first != __result.__last, "No exponent present");
333 if (*__first == '.') {
334 __result.__radix_point = __first;
335 __result.__exponent = __formatter::__find_exponent(__first + 1, __result.__last);
336 } else {
337 __result.__radix_point = __result.__last;
338 __result.__exponent = __first;
339 }
340
341 // clang-format off
342 _LIBCPP_ASSERT((__result.__integral != __result.__last) &&
343 (__result.__radix_point == __result.__last || *__result.__radix_point == '.') &&
344 (__result.__exponent != __result.__last && *__result.__exponent == 'e'),
345 "Post-condition failure.");
346 // clang-format on
347 return __result;
348 }
349
350 template <class _Fp, class _Tp>
351 _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_scientific_upper_case(const __float_buffer<_Fp>& __buffer,
352 _Tp __value, int __precision,
353 char* __integral) {
354 __float_result __result =
355 __formatter::__format_buffer_scientific_lower_case(__buffer, __value, __precision, __integral);
356 *__result.__exponent = 'E';
357 return __result;
358 }
359
360 template <class _Fp, class _Tp>
361 _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_fixed(const __float_buffer<_Fp>& __buffer, _Tp __value,
362 int __precision, char* __integral) {
363 __float_result __result;
364 __result.__integral = __integral;
365 __result.__last = __formatter::__to_buffer(__integral, __buffer.end(), __value, chars_format::fixed, __precision);
366
367 // When there's no precision there's no radix point.
368 // Else the radix point is placed at __precision + 1 from the end.
369 // By converting __precision to a bool the subtraction can be done
370 // unconditionally.
371 __result.__radix_point = __result.__last - (__precision + bool(__precision));
372 __result.__exponent = __result.__last;
373
374 // clang-format off
375 _LIBCPP_ASSERT((__result.__integral != __result.__last) &&
376 (__result.__radix_point == __result.__last || *__result.__radix_point == '.') &&
377 (__result.__exponent == __result.__last),
378 "Post-condition failure.");
379 // clang-format on
380 return __result;
381 }
382
383 template <class _Fp, class _Tp>
384 _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_general_lower_case(__float_buffer<_Fp>& __buffer, _Tp __value,
385 int __precision, char* __integral) {
386
387 __buffer.__remove_trailing_zeros();
388
389 __float_result __result;
390 __result.__integral = __integral;
391 __result.__last = __formatter::__to_buffer(__integral, __buffer.end(), __value, chars_format::general, __precision);
392
393 char* __first = __integral + 1;
394 if (__first == __result.__last) {
395 __result.__radix_point = __result.__last;
396 __result.__exponent = __result.__last;
397 } else {
398 __result.__exponent = __formatter::__find_exponent(__first, __result.__last);
399 if (__result.__exponent != __result.__last)
400 // In scientific mode if there's a radix point it will always be after
401 // the first digit. (This is the position __first points at).
402 __result.__radix_point = *__first == '.' ? __first : __result.__last;
403 else {
404 // In fixed mode the algorithm truncates trailing spaces and possibly the
405 // radix point. There's no good guess for the position of the radix point
406 // therefore scan the output after the first digit.
407 __result.__radix_point = _VSTD::find(__first, __result.__last, '.');
408 }
409 }
410
411 // clang-format off
412 _LIBCPP_ASSERT((__result.__integral != __result.__last) &&
413 (__result.__radix_point == __result.__last || *__result.__radix_point == '.') &&
414 (__result.__exponent == __result.__last || *__result.__exponent == 'e'),
415 "Post-condition failure.");
416 // clang-format on
417
418 return __result;
419 }
420
421 template <class _Fp, class _Tp>
422 _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer_general_upper_case(__float_buffer<_Fp>& __buffer, _Tp __value,
423 int __precision, char* __integral) {
424 __float_result __result = __formatter::__format_buffer_general_lower_case(__buffer, __value, __precision, __integral);
425 if (__result.__exponent != __result.__last)
426 *__result.__exponent = 'E';
427 return __result;
428 }
429
430 /// Fills the buffer with the data based on the requested formatting.
431 ///
432 /// This function, when needed, turns the characters to upper case and
433 /// determines the "interesting" locations which are returned to the caller.
434 ///
435 /// This means the caller never has to convert the contents of the buffer to
436 /// upper case or search for radix points and the location of the exponent.
437 /// This gives a bit of overhead. The original code didn't do that, but due
438 /// to the number of possible additional work needed to turn this number to
439 /// the proper output the code was littered with tests for upper cases and
440 /// searches for radix points and exponents.
441 /// - When a precision larger than the type's precision is selected
442 /// additional zero characters need to be written before the exponent.
443 /// - alternate form needs to add a radix point when not present.
444 /// - localization needs to do grouping in the integral part.
445 template <class _Fp, class _Tp>
446 // TODO FMT _Fp should just be _Tp when to_chars has proper long double support.
447 _LIBCPP_HIDE_FROM_ABI __float_result __format_buffer(
448 __float_buffer<_Fp>& __buffer,
449 _Tp __value,
450 bool __negative,
451 bool __has_precision,
452 __format_spec::__sign __sign,
453 __format_spec::__type __type) {
454 char* __first = __formatter::__insert_sign(__buffer.begin(), __negative, __sign);
455 switch (__type) {
456 case __format_spec::__type::__default:
457 if (__has_precision)
458 return __formatter::__format_buffer_general_lower_case(__buffer, __value, __buffer.__precision(), __first);
459 else
460 return __formatter::__format_buffer_default(__buffer, __value, __first);
461
462 case __format_spec::__type::__hexfloat_lower_case:
463 return __formatter::__format_buffer_hexadecimal_lower_case(
464 __buffer, __value, __has_precision ? __buffer.__precision() : -1, __first);
465
466 case __format_spec::__type::__hexfloat_upper_case:
467 return __formatter::__format_buffer_hexadecimal_upper_case(
468 __buffer, __value, __has_precision ? __buffer.__precision() : -1, __first);
469
470 case __format_spec::__type::__scientific_lower_case:
471 return __formatter::__format_buffer_scientific_lower_case(__buffer, __value, __buffer.__precision(), __first);
472
473 case __format_spec::__type::__scientific_upper_case:
474 return __formatter::__format_buffer_scientific_upper_case(__buffer, __value, __buffer.__precision(), __first);
475
476 case __format_spec::__type::__fixed_lower_case:
477 case __format_spec::__type::__fixed_upper_case:
478 return __formatter::__format_buffer_fixed(__buffer, __value, __buffer.__precision(), __first);
479
480 case __format_spec::__type::__general_lower_case:
481 return __formatter::__format_buffer_general_lower_case(__buffer, __value, __buffer.__precision(), __first);
482
483 case __format_spec::__type::__general_upper_case:
484 return __formatter::__format_buffer_general_upper_case(__buffer, __value, __buffer.__precision(), __first);
485
486 default:
487 _LIBCPP_ASSERT(false, "The parser should have validated the type");
488 __libcpp_unreachable();
489 }
490 }
491
492 # ifndef _LIBCPP_HAS_NO_LOCALIZATION
493 template <class _OutIt, class _Fp, class _CharT>
494 _LIBCPP_HIDE_FROM_ABI _OutIt __format_locale_specific_form(
495 _OutIt __out_it,
496 const __float_buffer<_Fp>& __buffer,
497 const __float_result& __result,
498 _VSTD::locale __loc,
499 __format_spec::__parsed_specifications<_CharT> __specs) {
500 const auto& __np = std::use_facet<numpunct<_CharT>>(__loc);
501 string __grouping = __np.grouping();
502 char* __first = __result.__integral;
503 // When no radix point or exponent are present __last will be __result.__last.
504 char* __last = _VSTD::min(__result.__radix_point, __result.__exponent);
505
506 ptrdiff_t __digits = __last - __first;
507 if (!__grouping.empty()) {
508 if (__digits <= __grouping[0])
509 __grouping.clear();
510 else
511 __grouping = __formatter::__determine_grouping(__digits, __grouping);
512 }
513
514 ptrdiff_t __size =
515 __result.__last - __buffer.begin() + // Formatted string
516 __buffer.__num_trailing_zeros() + // Not yet rendered zeros
517 __grouping.size() - // Grouping contains one
518 !__grouping.empty(); // additional character
519
520 __formatter::__padding_size_result __padding = {0, 0};
521 bool __zero_padding = __specs.__alignment_ == __format_spec::__alignment::__zero_padding;
522 if (__size < __specs.__width_) {
523 if (__zero_padding) {
524 __specs.__alignment_ = __format_spec::__alignment::__right;
525 __specs.__fill_ = _CharT('0');
526 }
527
528 __padding = __formatter::__padding_size(__size, __specs.__width_, __specs.__alignment_);
529 }
530
531 // sign and (zero padding or alignment)
532 if (__zero_padding && __first != __buffer.begin())
533 *__out_it++ = *__buffer.begin();
534 __out_it = __formatter::__fill(_VSTD::move(__out_it), __padding.__before_, __specs.__fill_);
535 if (!__zero_padding && __first != __buffer.begin())
536 *__out_it++ = *__buffer.begin();
537
538 // integral part
539 if (__grouping.empty()) {
540 __out_it = __formatter::__copy(__first, __digits, _VSTD::move(__out_it));
541 } else {
542 auto __r = __grouping.rbegin();
543 auto __e = __grouping.rend() - 1;
544 _CharT __sep = __np.thousands_sep();
545 // The output is divided in small groups of numbers to write:
546 // - A group before the first separator.
547 // - A separator and a group, repeated for the number of separators.
548 // - A group after the last separator.
549 // This loop achieves that process by testing the termination condition
550 // midway in the loop.
551 while (true) {
552 __out_it = __formatter::__copy(__first, *__r, _VSTD::move(__out_it));
553 __first += *__r;
554
555 if (__r == __e)
556 break;
557
558 ++__r;
559 *__out_it++ = __sep;
560 }
561 }
562
563 // fractional part
564 if (__result.__radix_point != __result.__last) {
565 *__out_it++ = __np.decimal_point();
566 __out_it = __formatter::__copy(__result.__radix_point + 1, __result.__exponent, _VSTD::move(__out_it));
567 __out_it = __formatter::__fill(_VSTD::move(__out_it), __buffer.__num_trailing_zeros(), _CharT('0'));
568 }
569
570 // exponent
571 if (__result.__exponent != __result.__last)
572 __out_it = __formatter::__copy(__result.__exponent, __result.__last, _VSTD::move(__out_it));
573
574 // alignment
575 return __formatter::__fill(_VSTD::move(__out_it), __padding.__after_, __specs.__fill_);
576 }
577 # endif // _LIBCPP_HAS_NO_LOCALIZATION
578
579 template <class _OutIt, class _CharT>
580 _LIBCPP_HIDE_FROM_ABI _OutIt __format_floating_point_non_finite(
581 _OutIt __out_it, __format_spec::__parsed_specifications<_CharT> __specs, bool __negative, bool __isnan) {
582 char __buffer[4];
583 char* __last = __formatter::__insert_sign(__buffer, __negative, __specs.__std_.__sign_);
584
585 // to_chars can return inf, infinity, nan, and nan(n-char-sequence).
586 // The format library requires inf and nan.
587 // All in one expression to avoid dangling references.
588 bool __upper_case =
589 __specs.__std_.__type_ == __format_spec::__type::__hexfloat_upper_case ||
590 __specs.__std_.__type_ == __format_spec::__type::__scientific_upper_case ||
591 __specs.__std_.__type_ == __format_spec::__type::__fixed_upper_case ||
592 __specs.__std_.__type_ == __format_spec::__type::__general_upper_case;
593 __last = _VSTD::copy_n(&("infnanINFNAN"[6 * __upper_case + 3 * __isnan]), 3, __last);
594
595 // [format.string.std]/13
596 // A zero (0) character preceding the width field pads the field with
597 // leading zeros (following any indication of sign or base) to the field
598 // width, except when applied to an infinity or NaN.
599 if (__specs.__alignment_ == __format_spec::__alignment::__zero_padding)
600 __specs.__alignment_ = __format_spec::__alignment::__right;
601
602 return __formatter::__write(__buffer, __last, _VSTD::move(__out_it), __specs);
603 }
604
605 template <floating_point _Tp, class _CharT>
606 _LIBCPP_HIDE_FROM_ABI auto
607 __format_floating_point(_Tp __value, auto& __ctx, __format_spec::__parsed_specifications<_CharT> __specs)
608 -> decltype(__ctx.out()) {
609 bool __negative = _VSTD::signbit(__value);
610
611 if (!_VSTD::isfinite(__value)) [[unlikely]]
612 return __formatter::__format_floating_point_non_finite(__ctx.out(), __specs, __negative, _VSTD::isnan(__value));
613
614 // Depending on the std-format-spec string the sign and the value
615 // might not be outputted together:
616 // - zero-padding may insert additional '0' characters.
617 // Therefore the value is processed as a non negative value.
618 // The function @ref __insert_sign will insert a '-' when the value was
619 // negative.
620
621 if (__negative)
622 __value = -__value;
623
624 // TODO FMT _Fp should just be _Tp when to_chars has proper long double support.
625 using _Fp = conditional_t<same_as<_Tp, long double>, double, _Tp>;
626 // Force the type of the precision to avoid -1 to become an unsigned value.
627 __float_buffer<_Fp> __buffer(__specs.__precision_);
628 __float_result __result = __formatter::__format_buffer(
629 __buffer, __value, __negative, (__specs.__has_precision()), __specs.__std_.__sign_, __specs.__std_.__type_);
630
631 if (__specs.__std_.__alternate_form_) {
632 if (__result.__radix_point == __result.__last) {
633 *__result.__last++ = '.';
634
635 // When there is an exponent the point needs to be moved before the
636 // exponent. When there's no exponent the rotate does nothing. Since
637 // rotate tests whether the operation is a nop, call it unconditionally.
638 _VSTD::rotate(__result.__exponent, __result.__last - 1, __result.__last);
639 __result.__radix_point = __result.__exponent;
640
641 // The radix point is always placed before the exponent.
642 // - No exponent needs to point to the new last.
643 // - An exponent needs to move one position to the right.
644 // So it's safe to increment the value unconditionally.
645 ++__result.__exponent;
646 }
647
648 // [format.string.std]/6
649 // In addition, for g and G conversions, trailing zeros are not removed
650 // from the result.
651 //
652 // If the type option for a floating-point type is none it may use the
653 // general formatting, but it's not a g or G conversion. So in that case
654 // the formatting should not append trailing zeros.
655 bool __is_general = __specs.__std_.__type_ == __format_spec::__type::__general_lower_case ||
656 __specs.__std_.__type_ == __format_spec::__type::__general_upper_case;
657
658 if (__is_general) {
659 // https://en.cppreference.com/w/c/io/fprintf
660 // Let P equal the precision if nonzero, 6 if the precision is not
661 // specified, or 1 if the precision is 0. Then, if a conversion with
662 // style E would have an exponent of X:
663 int __p = _VSTD::max(1, (__specs.__has_precision() ? __specs.__precision_ : 6));
664 if (__result.__exponent == __result.__last)
665 // if P > X >= -4, the conversion is with style f or F and precision P - 1 - X.
666 // By including the radix point it calculates P - (1 + X)
667 __p -= __result.__radix_point - __result.__integral;
668 else
669 // otherwise, the conversion is with style e or E and precision P - 1.
670 --__p;
671
672 ptrdiff_t __precision = (__result.__exponent - __result.__radix_point) - 1;
673 if (__precision < __p)
674 __buffer.__add_trailing_zeros(__p - __precision);
675 }
676 }
677
678 # ifndef _LIBCPP_HAS_NO_LOCALIZATION
679 if (__specs.__std_.__locale_specific_form_)
680 return __formatter::__format_locale_specific_form(__ctx.out(), __buffer, __result, __ctx.locale(), __specs);
681 # endif
682
683 ptrdiff_t __size = __result.__last - __buffer.begin();
684 int __num_trailing_zeros = __buffer.__num_trailing_zeros();
685 if (__size + __num_trailing_zeros >= __specs.__width_) {
686 if (__num_trailing_zeros && __result.__exponent != __result.__last)
687 // Insert trailing zeros before exponent character.
688 return __formatter::__copy(
689 __result.__exponent,
690 __result.__last,
691 __formatter::__fill(__formatter::__copy(__buffer.begin(), __result.__exponent, __ctx.out()),
692 __num_trailing_zeros,
693 _CharT('0')));
694
695 return __formatter::__fill(
696 __formatter::__copy(__buffer.begin(), __result.__last, __ctx.out()), __num_trailing_zeros, _CharT('0'));
697 }
698
699 auto __out_it = __ctx.out();
700 char* __first = __buffer.begin();
701 if (__specs.__alignment_ == __format_spec::__alignment ::__zero_padding) {
702 // When there is a sign output it before the padding. Note the __size
703 // doesn't need any adjustment, regardless whether the sign is written
704 // here or in __formatter::__write.
705 if (__first != __result.__integral)
706 *__out_it++ = *__first++;
707 // After the sign is written, zero padding is the same a right alignment
708 // with '0'.
709 __specs.__alignment_ = __format_spec::__alignment::__right;
710 __specs.__fill_ = _CharT('0');
711 }
712
713 if (__num_trailing_zeros)
714 return __formatter::__write_using_trailing_zeros(
715 __first, __result.__last, _VSTD::move(__out_it), __specs, __size, __result.__exponent, __num_trailing_zeros);
716
717 return __formatter::__write(__first, __result.__last, _VSTD::move(__out_it), __specs, __size);
718 }
719
720 } // namespace __formatter
721
722 template <__fmt_char_type _CharT>
723 struct _LIBCPP_TEMPLATE_VIS __formatter_floating_point {
724 public:
725 _LIBCPP_HIDE_FROM_ABI constexpr auto
726 parse(basic_format_parse_context<_CharT>& __parse_ctx) -> decltype(__parse_ctx.begin()) {
727 auto __result = __parser_.__parse(__parse_ctx, __format_spec::__fields_floating_point);
728 __format_spec::__process_parsed_floating_point(__parser_);
729 return __result;
730 }
731
732 template <floating_point _Tp>
733 _LIBCPP_HIDE_FROM_ABI auto format(_Tp __value, auto& __ctx) const -> decltype(__ctx.out()) {
734 return __formatter::__format_floating_point(__value, __ctx, __parser_.__get_parsed_std_specifications(__ctx));
735 }
736
737 __format_spec::__parser<_CharT> __parser_;
738 };
739
740 template <__fmt_char_type _CharT>
741 struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter<float, _CharT>
742 : public __formatter_floating_point<_CharT> {};
743 template <__fmt_char_type _CharT>
744 struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter<double, _CharT>
745 : public __formatter_floating_point<_CharT> {};
746 template <__fmt_char_type _CharT>
747 struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter<long double, _CharT>
748 : public __formatter_floating_point<_CharT> {};
749
750 #endif //_LIBCPP_STD_VER > 17
751
752 _LIBCPP_END_NAMESPACE_STD
753
754 _LIBCPP_POP_MACROS
755
756 #endif // _LIBCPP___FORMAT_FORMATTER_FLOATING_POINT_H
757