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