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.h>
14 #include <__algorithm/copy_n.h>
15 #include <__algorithm/fill_n.h>
16 #include <__algorithm/find.h>
17 #include <__algorithm/min.h>
18 #include <__algorithm/rotate.h>
19 #include <__algorithm/transform.h>
20 #include <__concepts/arithmetic.h>
21 #include <__concepts/same_as.h>
22 #include <__config>
23 #include <__format/format_fwd.h>
24 #include <__format/format_parse_context.h>
25 #include <__format/formatter.h>
26 #include <__format/formatter_integral.h>
27 #include <__format/formatter_output.h>
28 #include <__format/parser_std_format_spec.h>
29 #include <__memory/allocator.h>
30 #include <__utility/move.h>
31 #include <__utility/unreachable.h>
32 #include <charconv>
33 
34 #ifndef _LIBCPP_HAS_NO_LOCALIZATION
35 #  include <locale>
36 #endif
37 
38 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
39 #  pragma GCC system_header
40 #endif
41 
42 _LIBCPP_PUSH_MACROS
43 #include <__undef_macros>
44 
45 _LIBCPP_BEGIN_NAMESPACE_STD
46 
47 #if _LIBCPP_STD_VER > 17
48 
49 namespace __formatter {
50 
51 template <floating_point _Tp>
52 _LIBCPP_HIDE_FROM_ABI char* __to_buffer(char* __first, char* __last, _Tp __value) {
53   to_chars_result __r = _VSTD::to_chars(__first, __last, __value);
54   _LIBCPP_ASSERT(__r.ec == errc(0), "Internal buffer too small");
55   return __r.ptr;
56 }
57 
58 template <floating_point _Tp>
59 _LIBCPP_HIDE_FROM_ABI char* __to_buffer(char* __first, char* __last, _Tp __value, chars_format __fmt) {
60   to_chars_result __r = _VSTD::to_chars(__first, __last, __value, __fmt);
61   _LIBCPP_ASSERT(__r.ec == errc(0), "Internal buffer too small");
62   return __r.ptr;
63 }
64 
65 template <floating_point _Tp>
66 _LIBCPP_HIDE_FROM_ABI char* __to_buffer(char* __first, char* __last, _Tp __value, chars_format __fmt, int __precision) {
67   to_chars_result __r = _VSTD::to_chars(__first, __last, __value, __fmt, __precision);
68   _LIBCPP_ASSERT(__r.ec == errc(0), "Internal buffer too small");
69   return __r.ptr;
70 }
71 
72 // https://en.cppreference.com/w/cpp/language/types#cite_note-1
73 // float             min subnormal: +/-0x1p-149   max: +/- 3.402,823,4 10^38
74 // double            min subnormal: +/-0x1p-1074  max  +/- 1.797,693,134,862,315,7 10^308
75 // long double (x86) min subnormal: +/-0x1p-16446 max: +/- 1.189,731,495,357,231,765,021 10^4932
76 //
77 // The maximum number of digits required for the integral part is based on the
78 // maximum's value power of 10. Every power of 10 requires one additional
79 // decimal digit.
80 // The maximum number of digits required for the fractional part is based on
81 // the minimal subnormal hexadecimal output's power of 10. Every division of a
82 // fraction's binary 1 by 2, requires one additional decimal digit.
83 //
84 // The maximum size of a formatted value depends on the selected output format.
85 // Ignoring the fact the format string can request a precision larger than the
86 // values maximum required, these values are:
87 //
88 // sign                    1 code unit
89 // __max_integral
90 // radix point             1 code unit
91 // __max_fractional
92 // exponent character      1 code unit
93 // sign                    1 code unit
94 // __max_fractional_value
95 // -----------------------------------
96 // total                   4 code units extra required.
97 //
98 // TODO FMT Optimize the storage to avoid storing digits that are known to be zero.
99 // https://www.exploringbinary.com/maximum-number-of-decimal-digits-in-binary-floating-point-numbers/
100 
101 // TODO FMT Add long double specialization when to_chars has proper long double support.
102 template <class _Tp>
103 struct __traits;
104 
105 template <floating_point _Fp>
106 static constexpr size_t __float_buffer_size(int __precision) {
107   using _Traits = __traits<_Fp>;
108   return 4 + _Traits::__max_integral + __precision + _Traits::__max_fractional_value;
109 }
110 
111 template <>
112 struct __traits<float> {
113   static constexpr int __max_integral = 38;
114   static constexpr int __max_fractional = 149;
115   static constexpr int __max_fractional_value = 3;
116   static constexpr size_t __stack_buffer_size = 256;
117 
118   static constexpr int __hex_precision_digits = 3;
119 };
120 
121 template <>
122 struct __traits<double> {
123   static constexpr int __max_integral = 308;
124   static constexpr int __max_fractional = 1074;
125   static constexpr int __max_fractional_value = 4;
126   static constexpr size_t __stack_buffer_size = 1024;
127 
128   static constexpr int __hex_precision_digits = 4;
129 };
130 
131 /// Helper class to store the conversion buffer.
132 ///
133 /// Depending on the maxium size required for a value, the buffer is allocated
134 /// on the stack or the heap.
135 template <floating_point _Fp>
136 class _LIBCPP_TEMPLATE_VIS __float_buffer {
137   using _Traits = __traits<_Fp>;
138 
139 public:
140   // TODO FMT Improve this constructor to do a better estimate.
141   // When using a scientific formatting with a precision of 6 a stack buffer
142   // will always suffice. At the moment that isn't important since floats and
143   // doubles use a stack buffer, unless the precision used in the format string
144   // is large.
145   // When supporting long doubles the __max_integral part becomes 4932 which
146   // may be too much for some platforms. For these cases a better estimate is
147   // required.
148   explicit _LIBCPP_HIDE_FROM_ABI __float_buffer(int __precision)
149       : __precision_(__precision != -1 ? __precision : _Traits::__max_fractional) {
150 
151     // When the precision is larger than _Traits::__max_fractional the digits in
152     // the range (_Traits::__max_fractional, precision] will contain the value
153     // zero. There's no need to request to_chars to write these zeros:
154     // - When the value is large a temporary heap buffer needs to be allocated.
155     // - When to_chars writes the values they need to be "copied" to the output:
156     //   - char: std::fill on the output iterator is faster than std::copy.
157     //   - wchar_t: same argument as char, but additional std::copy won't work.
158     //     The input is always a char buffer, so every char in the buffer needs
159     //     to be converted from a char to a wchar_t.
160     if (__precision_ > _Traits::__max_fractional) {
161       __num_trailing_zeros_ = __precision_ - _Traits::__max_fractional;
162       __precision_ = _Traits::__max_fractional;
163     }
164 
165     __size_ = __formatter::__float_buffer_size<_Fp>(__precision_);
166     if (__size_ > _Traits::__stack_buffer_size)
167       // The allocated buffer's contents don't need initialization.
168       __begin_ = allocator<char>{}.allocate(__size_);
169     else
170       __begin_ = __buffer_;
171   }
172 
173   _LIBCPP_HIDE_FROM_ABI ~__float_buffer() {
174     if (__size_ > _Traits::__stack_buffer_size)
175       allocator<char>{}.deallocate(__begin_, __size_);
176   }
177   _LIBCPP_HIDE_FROM_ABI __float_buffer(const __float_buffer&) = delete;
178   _LIBCPP_HIDE_FROM_ABI __float_buffer& operator=(const __float_buffer&) = delete;
179 
180   _LIBCPP_HIDE_FROM_ABI char* begin() const { return __begin_; }
181   _LIBCPP_HIDE_FROM_ABI char* end() const { return __begin_ + __size_; }
182 
183   _LIBCPP_HIDE_FROM_ABI int __precision() const { return __precision_; }
184   _LIBCPP_HIDE_FROM_ABI int __num_trailing_zeros() const { return __num_trailing_zeros_; }
185   _LIBCPP_HIDE_FROM_ABI void __remove_trailing_zeros() { __num_trailing_zeros_ = 0; }
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     return __formatter::__format_buffer_default(__buffer, __value, __first);
458 
459   case __format_spec::__type::__hexfloat_lower_case:
460     return __formatter::__format_buffer_hexadecimal_lower_case(
461         __buffer, __value, __has_precision ? __buffer.__precision() : -1, __first);
462 
463   case __format_spec::__type::__hexfloat_upper_case:
464     return __formatter::__format_buffer_hexadecimal_upper_case(
465         __buffer, __value, __has_precision ? __buffer.__precision() : -1, __first);
466 
467   case __format_spec::__type::__scientific_lower_case:
468     return __formatter::__format_buffer_scientific_lower_case(__buffer, __value, __buffer.__precision(), __first);
469 
470   case __format_spec::__type::__scientific_upper_case:
471     return __formatter::__format_buffer_scientific_upper_case(__buffer, __value, __buffer.__precision(), __first);
472 
473   case __format_spec::__type::__fixed_lower_case:
474   case __format_spec::__type::__fixed_upper_case:
475     return __formatter::__format_buffer_fixed(__buffer, __value, __buffer.__precision(), __first);
476 
477   case __format_spec::__type::__general_lower_case:
478     return __formatter::__format_buffer_general_lower_case(__buffer, __value, __buffer.__precision(), __first);
479 
480   case __format_spec::__type::__general_upper_case:
481     return __formatter::__format_buffer_general_upper_case(__buffer, __value, __buffer.__precision(), __first);
482 
483   default:
484     _LIBCPP_ASSERT(false, "The parser should have validated the type");
485     __libcpp_unreachable();
486   }
487 }
488 
489 #  ifndef _LIBCPP_HAS_NO_LOCALIZATION
490 template <class _OutIt, class _Fp, class _CharT>
491 _LIBCPP_HIDE_FROM_ABI _OutIt __format_locale_specific_form(
492     _OutIt __out_it,
493     const __float_buffer<_Fp>& __buffer,
494     const __float_result& __result,
495     _VSTD::locale __loc,
496     __format_spec::__parsed_specifications<_CharT> __specs) {
497   const auto& __np = use_facet<numpunct<_CharT>>(__loc);
498   string __grouping = __np.grouping();
499   char* __first = __result.__integral;
500   // When no radix point or exponent are present __last will be __result.__last.
501   char* __last = _VSTD::min(__result.__radix_point, __result.__exponent);
502 
503   ptrdiff_t __digits = __last - __first;
504   if (!__grouping.empty()) {
505     if (__digits <= __grouping[0])
506       __grouping.clear();
507     else
508       __grouping = __formatter::__determine_grouping(__digits, __grouping);
509   }
510 
511   ptrdiff_t __size =
512       __result.__last - __buffer.begin() + // Formatted string
513       __buffer.__num_trailing_zeros() +    // Not yet rendered zeros
514       __grouping.size() -                  // Grouping contains one
515       !__grouping.empty();                 // additional character
516 
517   __formatter::__padding_size_result __padding    = {0, 0};
518   bool __zero_padding                             = __specs.__alignment_ == __format_spec::__alignment::__zero_padding;
519   if (__size < __specs.__width_) {
520     if (__zero_padding) {
521       __specs.__alignment_ = __format_spec::__alignment::__right;
522       __specs.__fill_      = _CharT('0');
523     }
524 
525     __padding = __formatter::__padding_size(__size, __specs.__width_, __specs.__alignment_);
526   }
527 
528   // sign and (zero padding or alignment)
529   if (__zero_padding && __first != __buffer.begin())
530     *__out_it++ = *__buffer.begin();
531   __out_it = _VSTD::fill_n(_VSTD::move(__out_it), __padding.__before_, __specs.__fill_);
532   if (!__zero_padding && __first != __buffer.begin())
533     *__out_it++ = *__buffer.begin();
534 
535   // integral part
536   if (__grouping.empty()) {
537     __out_it = _VSTD::copy_n(__first, __digits, _VSTD::move(__out_it));
538   } else {
539     auto __r = __grouping.rbegin();
540     auto __e = __grouping.rend() - 1;
541     _CharT __sep = __np.thousands_sep();
542     // The output is divided in small groups of numbers to write:
543     // - A group before the first separator.
544     // - A separator and a group, repeated for the number of separators.
545     // - A group after the last separator.
546     // This loop achieves that process by testing the termination condition
547     // midway in the loop.
548     while (true) {
549       __out_it = _VSTD::copy_n(__first, *__r, _VSTD::move(__out_it));
550       __first += *__r;
551 
552       if (__r == __e)
553         break;
554 
555       ++__r;
556       *__out_it++ = __sep;
557     }
558   }
559 
560   // fractional part
561   if (__result.__radix_point != __result.__last) {
562     *__out_it++ = __np.decimal_point();
563     __out_it = _VSTD::copy(__result.__radix_point + 1, __result.__exponent, _VSTD::move(__out_it));
564     __out_it = _VSTD::fill_n(_VSTD::move(__out_it), __buffer.__num_trailing_zeros(), _CharT('0'));
565   }
566 
567   // exponent
568   if (__result.__exponent != __result.__last)
569     __out_it = _VSTD::copy(__result.__exponent, __result.__last, _VSTD::move(__out_it));
570 
571   // alignment
572   return _VSTD::fill_n(_VSTD::move(__out_it), __padding.__after_, __specs.__fill_);
573 }
574 #  endif // _LIBCPP_HAS_NO_LOCALIZATION
575 
576 template <class _OutIt, class _CharT>
577 _LIBCPP_HIDE_FROM_ABI _OutIt __format_floating_point_non_finite(
578     _OutIt __out_it, __format_spec::__parsed_specifications<_CharT> __specs, bool __negative, bool __isnan) {
579   char __buffer[4];
580   char* __last = __formatter::__insert_sign(__buffer, __negative, __specs.__std_.__sign_);
581 
582   // to_chars can return inf, infinity, nan, and nan(n-char-sequence).
583   // The format library requires inf and nan.
584   // All in one expression to avoid dangling references.
585   bool __upper_case =
586       __specs.__std_.__type_ == __format_spec::__type::__hexfloat_upper_case ||
587       __specs.__std_.__type_ == __format_spec::__type::__scientific_upper_case ||
588       __specs.__std_.__type_ == __format_spec::__type::__fixed_upper_case ||
589       __specs.__std_.__type_ == __format_spec::__type::__general_upper_case;
590   __last = _VSTD::copy_n(&("infnanINFNAN"[6 * __upper_case + 3 * __isnan]), 3, __last);
591 
592   // [format.string.std]/13
593   // A zero (0) character preceding the width field pads the field with
594   // leading zeros (following any indication of sign or base) to the field
595   // width, except when applied to an infinity or NaN.
596   if (__specs.__alignment_ == __format_spec::__alignment::__zero_padding)
597     __specs.__alignment_ = __format_spec::__alignment::__right;
598 
599   return __formatter::__write(__buffer, __last, _VSTD::move(__out_it), __specs);
600 }
601 
602 template <floating_point _Tp, class _CharT>
603 _LIBCPP_HIDE_FROM_ABI auto
604 __format_floating_point(_Tp __value, auto& __ctx, __format_spec::__parsed_specifications<_CharT> __specs)
605     -> decltype(__ctx.out()) {
606   bool __negative = _VSTD::signbit(__value);
607 
608   if (!_VSTD::isfinite(__value)) [[unlikely]]
609     return __formatter::__format_floating_point_non_finite(__ctx.out(), __specs, __negative, _VSTD::isnan(__value));
610 
611   // Depending on the std-format-spec string the sign and the value
612   // might not be outputted together:
613   // - zero-padding may insert additional '0' characters.
614   // Therefore the value is processed as a non negative value.
615   // The function @ref __insert_sign will insert a '-' when the value was
616   // negative.
617 
618   if (__negative)
619     __value = -__value;
620 
621   // TODO FMT _Fp should just be _Tp when to_chars has proper long double support.
622   using _Fp = conditional_t<same_as<_Tp, long double>, double, _Tp>;
623   // Force the type of the precision to avoid -1 to become an unsigned value.
624   __float_buffer<_Fp> __buffer(__specs.__precision_);
625   __float_result __result = __formatter::__format_buffer(
626       __buffer, __value, __negative, (__specs.__has_precision()), __specs.__std_.__sign_, __specs.__std_.__type_);
627 
628   if (__specs.__std_.__alternate_form_ && __result.__radix_point == __result.__last) {
629     *__result.__last++ = '.';
630 
631     // When there is an exponent the point needs to be moved before the
632     // exponent. When there's no exponent the rotate does nothing. Since
633     // rotate tests whether the operation is a nop, call it unconditionally.
634     _VSTD::rotate(__result.__exponent, __result.__last - 1, __result.__last);
635     __result.__radix_point = __result.__exponent;
636 
637     // The radix point is always placed before the exponent.
638     // - No exponent needs to point to the new last.
639     // - An exponent needs to move one position to the right.
640     // So it's safe to increment the value unconditionally.
641     ++__result.__exponent;
642   }
643 
644 #  ifndef _LIBCPP_HAS_NO_LOCALIZATION
645   if (__specs.__std_.__locale_specific_form_)
646     return __formatter::__format_locale_specific_form(__ctx.out(), __buffer, __result, __ctx.locale(), __specs);
647 #  endif
648 
649   ptrdiff_t __size         = __result.__last - __buffer.begin();
650   int __num_trailing_zeros = __buffer.__num_trailing_zeros();
651   if (__size + __num_trailing_zeros >= __specs.__width_) {
652     if (__num_trailing_zeros && __result.__exponent != __result.__last)
653       // Insert trailing zeros before exponent character.
654       return _VSTD::copy(
655           __result.__exponent,
656           __result.__last,
657           _VSTD::fill_n(
658               _VSTD::copy(__buffer.begin(), __result.__exponent, __ctx.out()), __num_trailing_zeros, _CharT('0')));
659 
660     return _VSTD::fill_n(
661         _VSTD::copy(__buffer.begin(), __result.__last, __ctx.out()), __num_trailing_zeros, _CharT('0'));
662   }
663 
664   auto __out_it = __ctx.out();
665   char* __first = __buffer.begin();
666   if (__specs.__alignment_ == __format_spec::__alignment ::__zero_padding) {
667     // When there is a sign output it before the padding. Note the __size
668     // doesn't need any adjustment, regardless whether the sign is written
669     // here or in __formatter::__write.
670     if (__first != __result.__integral)
671       *__out_it++ = *__first++;
672     // After the sign is written, zero padding is the same a right alignment
673     // with '0'.
674     __specs.__alignment_ = __format_spec::__alignment::__right;
675     __specs.__fill_      = _CharT('0');
676   }
677 
678   if (__num_trailing_zeros)
679     return __formatter::__write_using_trailing_zeros(
680         __first, __result.__last, _VSTD::move(__out_it), __specs, __size, __result.__exponent, __num_trailing_zeros);
681 
682   return __formatter::__write(__first, __result.__last, _VSTD::move(__out_it), __specs, __size);
683 }
684 
685 } // namespace __formatter
686 
687 template <__formatter::__char_type _CharT>
688 struct _LIBCPP_TEMPLATE_VIS __formatter_floating_point {
689 public:
690   _LIBCPP_HIDE_FROM_ABI constexpr auto
691   parse(basic_format_parse_context<_CharT>& __parse_ctx) -> decltype(__parse_ctx.begin()) {
692     auto __result = __parser_.__parse(__parse_ctx, __format_spec::__fields_floating_point);
693     __format_spec::__process_parsed_floating_point(__parser_);
694     return __result;
695   }
696 
697   template <floating_point _Tp>
698   _LIBCPP_HIDE_FROM_ABI auto format(_Tp __value, auto& __ctx) const -> decltype(__ctx.out()) {
699     return __formatter::__format_floating_point(__value, __ctx, __parser_.__get_parsed_std_specifications(__ctx));
700   }
701 
702   __format_spec::__parser<_CharT> __parser_;
703 };
704 
705 template <__formatter::__char_type _CharT>
706 struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter<float, _CharT>
707     : public __formatter_floating_point<_CharT> {};
708 template <__formatter::__char_type _CharT>
709 struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter<double, _CharT>
710     : public __formatter_floating_point<_CharT> {};
711 template <__formatter::__char_type _CharT>
712 struct _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT formatter<long double, _CharT>
713     : public __formatter_floating_point<_CharT> {};
714 
715 #endif //_LIBCPP_STD_VER > 17
716 
717 _LIBCPP_END_NAMESPACE_STD
718 
719 _LIBCPP_POP_MACROS
720 
721 #endif // _LIBCPP___FORMAT_FORMATTER_FLOATING_POINT_H
722