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