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