[libc] Add platform independent floating point rounding mode checks.
[llvm-project.git] / libc / src / stdio / printf_core / float_dec_converter.h
blobbe4b2831d80638b093426bbe969b5c5b4fca290f
1 //===-- Decimal Float Converter for printf ----------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_LIBC_SRC_STDIO_PRINTF_CORE_FLOAT_DEC_CONVERTER_H
10 #define LLVM_LIBC_SRC_STDIO_PRINTF_CORE_FLOAT_DEC_CONVERTER_H
12 #include "src/__support/CPP/string_view.h"
13 #include "src/__support/FPUtil/FEnvImpl.h"
14 #include "src/__support/FPUtil/FPBits.h"
15 #include "src/__support/FPUtil/FloatProperties.h"
16 #include "src/__support/FPUtil/rounding_mode.h"
17 #include "src/__support/UInt.h"
18 #include "src/__support/UInt128.h"
19 #include "src/__support/common.h"
20 #include "src/__support/float_to_string.h"
21 #include "src/__support/integer_to_string.h"
22 #include "src/__support/libc_assert.h"
23 #include "src/stdio/printf_core/converter_utils.h"
24 #include "src/stdio/printf_core/core_structs.h"
25 #include "src/stdio/printf_core/float_inf_nan_converter.h"
26 #include "src/stdio/printf_core/writer.h"
28 #include <inttypes.h>
29 #include <stddef.h>
31 namespace __llvm_libc {
32 namespace printf_core {
34 using MantissaInt = fputil::FPBits<long double>::UIntType;
36 // Returns true if value is divisible by 2^p.
37 LIBC_INLINE constexpr bool multiple_of_power_of_2(const uint64_t value,
38 const uint32_t p) {
39 return (value & ((uint64_t(1) << p) - 1)) == 0;
42 constexpr size_t BLOCK_SIZE = 9;
43 constexpr uint32_t MAX_BLOCK = 999999999;
45 // constexpr size_t BLOCK_SIZE = 18;
46 // constexpr uint32_t MAX_BLOCK = 999999999999999999;
47 constexpr char DECIMAL_POINT = '.';
49 // This is used to represent which direction the number should be rounded.
50 enum class RoundDirection { Up, Down, Even };
52 class PaddingWriter {
53 bool left_justified = false;
54 bool leading_zeroes = false;
55 char sign_char = 0;
56 size_t min_width = 0;
58 public:
59 PaddingWriter() {}
60 PaddingWriter(const FormatSection &to_conv, char init_sign_char)
61 : left_justified((to_conv.flags & FormatFlags::LEFT_JUSTIFIED) > 0),
62 leading_zeroes((to_conv.flags & FormatFlags::LEADING_ZEROES) > 0),
63 sign_char(init_sign_char),
64 min_width(to_conv.min_width > 0 ? to_conv.min_width : 0) {}
66 int write_left_padding(Writer *writer, size_t total_digits) {
67 // The pattern is (spaces) (sign) (zeroes), but only one of spaces and
68 // zeroes can be written, and only if the padding amount is positive.
69 int padding_amount = min_width - total_digits - (sign_char > 0 ? 1 : 0);
70 if (left_justified || padding_amount < 0) {
71 if (sign_char > 0) {
72 RET_IF_RESULT_NEGATIVE(writer->write(sign_char));
74 return 0;
76 if (!leading_zeroes) {
77 RET_IF_RESULT_NEGATIVE(writer->write(' ', padding_amount));
79 if (sign_char > 0) {
80 RET_IF_RESULT_NEGATIVE(writer->write(sign_char));
82 if (leading_zeroes) {
83 RET_IF_RESULT_NEGATIVE(writer->write('0', padding_amount));
85 return 0;
88 int write_right_padding(Writer *writer, size_t total_digits) {
89 // If and only if the conversion is left justified, there may be trailing
90 // spaces.
91 int padding_amount = min_width - total_digits - (sign_char > 0 ? 1 : 0);
92 if (left_justified && padding_amount > 0) {
93 RET_IF_RESULT_NEGATIVE(writer->write(' ', padding_amount));
95 return 0;
100 We only need to round a given segment if all of the segments below it are
101 the max (or this is the last segment). This means that we don't have to
102 write those initially, we can just keep the most recent non-maximal
103 segment and a counter of the number of maximal segments. When we reach a
104 non-maximal segment, we write the stored segment as well as as many 9s as
105 are necessary. Alternately, if we reach the end and have to round up, then
106 we round the stored segment, and write zeroes following it. If this
107 crosses the decimal point, then we have to shift it one space to the
108 right.
109 This FloatWriter class does the buffering and counting, and writes to the
110 output when necessary.
112 class FloatWriter {
113 char block_buffer[BLOCK_SIZE]; // The buffer that holds a block.
114 size_t buffered_digits = 0; // The number of digits held in the buffer.
115 bool has_written = false; // True once any digits have been output.
116 size_t max_block_count = 0; // The # of blocks of all 9s currently buffered.
117 size_t total_digits = 0; // The number of digits that will be output.
118 size_t digits_before_decimal = 0; // The # of digits to write before the '.'
119 size_t total_digits_written = 0; // The # of digits that have been output.
120 bool has_decimal_point; // True if the number has a decimal point.
121 Writer *writer; // Writes to the final output.
122 PaddingWriter padding_writer; // Handles prefixes/padding, uses total_digits.
124 int flush_buffer() {
125 // Write the most recent buffered block, and mark has_written
126 if (!has_written) {
127 has_written = true;
128 RET_IF_RESULT_NEGATIVE(
129 padding_writer.write_left_padding(writer, total_digits));
132 // if the decimal point is the next character, or is in the range covered
133 // by the buffered block, write the appropriate digits and the decimal
134 // point.
135 if (total_digits_written < digits_before_decimal &&
136 total_digits_written + buffered_digits >= digits_before_decimal &&
137 has_decimal_point) {
138 size_t digits_to_write = digits_before_decimal - total_digits_written;
139 if (digits_to_write > 0) {
140 // Write the digits before the decimal point.
141 RET_IF_RESULT_NEGATIVE(writer->write({block_buffer, digits_to_write}));
143 RET_IF_RESULT_NEGATIVE(writer->write(DECIMAL_POINT));
144 if (buffered_digits - digits_to_write > 0) {
145 // Write the digits after the decimal point.
146 RET_IF_RESULT_NEGATIVE(
147 writer->write({block_buffer + digits_to_write,
148 (buffered_digits - digits_to_write)}));
150 // add 1 for the decimal point
151 total_digits_written += buffered_digits + 1;
152 // Mark the buffer as empty.
153 buffered_digits = 0;
156 // Clear the buffered digits.
157 if (buffered_digits > 0) {
158 RET_IF_RESULT_NEGATIVE(writer->write({block_buffer, buffered_digits}));
159 total_digits_written += buffered_digits;
160 buffered_digits = 0;
163 // if the decimal point is the next character, or is in the range covered
164 // by the max blocks, write the appropriate digits and the decimal point.
165 if (total_digits_written < digits_before_decimal &&
166 total_digits_written + BLOCK_SIZE * max_block_count >=
167 digits_before_decimal &&
168 has_decimal_point) {
169 size_t digits_to_write = digits_before_decimal - total_digits_written;
170 if (digits_to_write > 0) {
171 RET_IF_RESULT_NEGATIVE(writer->write('9', digits_to_write));
173 RET_IF_RESULT_NEGATIVE(writer->write(DECIMAL_POINT));
174 if ((BLOCK_SIZE * max_block_count) - digits_to_write > 0) {
175 RET_IF_RESULT_NEGATIVE(writer->write(
176 '9', (BLOCK_SIZE * max_block_count) - digits_to_write));
178 // add 1 for the decimal point
179 total_digits_written += BLOCK_SIZE * max_block_count + 1;
180 // clear the buffer of max blocks
181 max_block_count = 0;
184 // Clear the buffer of max blocks
185 if (max_block_count > 0) {
186 RET_IF_RESULT_NEGATIVE(writer->write('9', max_block_count * BLOCK_SIZE));
187 total_digits_written += max_block_count * BLOCK_SIZE;
188 max_block_count = 0;
190 return 0;
193 cpp::string_view exp_str(int exponent, cpp::span<char> exp_buffer) {
195 // -exponent will never overflow because all long double types we support
196 // have at most 15 bits of mantissa and the C standard defines an int as
197 // being at least 16 bits.
198 static_assert(fputil::FloatProperties<long double>::EXPONENT_WIDTH <
199 (sizeof(int) * 8));
201 int positive_exponent = exponent < 0 ? -exponent : exponent;
202 char exp_sign = exponent < 0 ? '-' : '+';
203 auto const int_to_str =
204 *IntegerToString::dec(positive_exponent, exp_buffer);
206 // IntegerToString writes the digits from right to left so there will be
207 // space to the left of int_to_str.
208 size_t digits_in_exp = int_to_str.size();
209 size_t index = exp_buffer.size() - digits_in_exp - 1;
211 // Ensure that at least two digits were written. IntegerToString always
212 // writes at least 1 digit (it writes "0" when the input number is 0).
213 if (digits_in_exp < 2) {
214 exp_buffer[index] = '0';
215 --index;
218 // Since the exp_buffer has to be sized to handle an intmax_t, it has space
219 // for a sign. In this case we're handling the sign on our own since we also
220 // want plus signs for positive numbers.
221 exp_buffer[index] = exp_sign;
223 return cpp::string_view(exp_buffer.data() + index,
224 exp_buffer.size() - index);
227 public:
228 FloatWriter(Writer *init_writer, bool init_has_decimal_point,
229 const PaddingWriter &init_padding_writer)
230 : has_decimal_point(init_has_decimal_point), writer(init_writer),
231 padding_writer(init_padding_writer) {}
233 void init(size_t init_total_digits, size_t init_digits_before_decimal) {
234 total_digits = init_total_digits;
235 digits_before_decimal = init_digits_before_decimal;
238 void write_first_block(BlockInt block, bool exp_format = false) {
239 char buf[IntegerToString::dec_bufsize<intmax_t>()];
240 auto const int_to_str = *IntegerToString::dec(block, buf);
241 size_t digits_buffered = int_to_str.size();
242 // Block Buffer is guaranteed to not overflow since block cannot have more
243 // than BLOCK_SIZE digits.
244 // TODO: Replace with memcpy
245 for (size_t count = 0; count < digits_buffered; ++count) {
246 block_buffer[count] = int_to_str[count];
248 buffered_digits = digits_buffered;
250 // In the exponent format (%e) we know how many digits will be written even
251 // before calculating any blocks, whereas the decimal format (%f) has to
252 // write all of the blocks that would come before the decimal place.
253 if (!exp_format) {
254 total_digits += digits_buffered;
255 digits_before_decimal += digits_buffered;
259 int write_middle_block(BlockInt block) {
260 if (block == MAX_BLOCK) { // Buffer max blocks in case of rounding
261 ++max_block_count;
262 } else { // If a non-max block has been found
263 RET_IF_RESULT_NEGATIVE(flush_buffer());
265 // Now buffer the current block. We add 1 + MAX_BLOCK to force the
266 // leading zeroes, and drop the leading one. This is probably inefficient,
267 // but it works. See https://xkcd.com/2021/
268 char buf[IntegerToString::dec_bufsize<intmax_t>()];
269 auto const int_to_str =
270 *IntegerToString::dec(block + (MAX_BLOCK + 1), buf);
271 // TODO: Replace with memcpy
272 for (size_t count = 0; count < BLOCK_SIZE; ++count) {
273 block_buffer[count] = int_to_str[count + 1];
276 buffered_digits = BLOCK_SIZE;
278 return 0;
281 int write_last_block_dec(BlockInt block, size_t block_digits,
282 RoundDirection round) {
283 char end_buff[BLOCK_SIZE];
285 char buf[IntegerToString::dec_bufsize<intmax_t>()];
286 auto const int_to_str = *IntegerToString::dec(block + (MAX_BLOCK + 1), buf);
288 // copy the last block_digits characters into the start of end_buff.
289 // TODO: Replace with memcpy
290 for (int count = block_digits - 1; count >= 0; --count) {
291 end_buff[count] = int_to_str[count + 1 + (BLOCK_SIZE - block_digits)];
294 char low_digit;
295 if (block_digits > 0) {
296 low_digit = end_buff[block_digits - 1];
297 } else if (max_block_count > 0) {
298 low_digit = '9';
299 } else {
300 low_digit = block_buffer[buffered_digits - 1];
303 // Round up
304 if (round == RoundDirection::Up ||
305 (round == RoundDirection::Even && low_digit % 2 != 0)) {
306 bool has_carry = true;
307 // handle the low block that we're adding
308 for (int count = block_digits - 1; count >= 0 && has_carry; --count) {
309 if (end_buff[count] == '9') {
310 end_buff[count] = '0';
311 } else {
312 end_buff[count] += 1;
313 has_carry = false;
316 // handle the high block that's buffered
317 for (int count = buffered_digits - 1; count >= 0 && has_carry; --count) {
318 if (block_buffer[count] == '9') {
319 block_buffer[count] = '0';
320 } else {
321 block_buffer[count] += 1;
322 has_carry = false;
326 // has_carry should only be true here if every previous digit is 9, which
327 // implies that the number has never been written.
328 if (has_carry /* && !has_written */) {
329 ++total_digits;
330 ++digits_before_decimal;
331 // Normally write_left_padding is called by flush_buffer but since we're
332 // rounding up all of the digits, the ones in the buffer are wrong and
333 // can't be flushed.
334 RET_IF_RESULT_NEGATIVE(
335 padding_writer.write_left_padding(writer, total_digits));
336 // Now we know we need to print a leading 1, zeroes up to the decimal
337 // point, the decimal point, and then finally digits after it.
338 RET_IF_RESULT_NEGATIVE(writer->write('1'));
339 // digits_before_decimal - 1 to account for the leading '1'
340 RET_IF_RESULT_NEGATIVE(writer->write('0', digits_before_decimal - 1));
341 if (has_decimal_point) {
342 RET_IF_RESULT_NEGATIVE(writer->write(DECIMAL_POINT));
343 // add one to digits_before_decimal to account for the decimal point
344 // itself.
345 if (total_digits > digits_before_decimal + 1) {
346 RET_IF_RESULT_NEGATIVE(
347 writer->write('0', total_digits - (digits_before_decimal + 1)));
350 total_digits_written = total_digits;
351 return 0;
354 // Either we intend to round down, or the rounding up is complete. Flush the
355 // buffers.
357 RET_IF_RESULT_NEGATIVE(flush_buffer());
359 // And then write the final block.
360 RET_IF_RESULT_NEGATIVE(writer->write({end_buff, block_digits}));
361 total_digits_written += block_digits;
362 return 0;
365 int write_last_block_exp(uint32_t block, size_t block_digits,
366 RoundDirection round, int exponent, char exp_char) {
367 char end_buff[BLOCK_SIZE];
370 char buf[IntegerToString::dec_bufsize<intmax_t>()];
371 auto const int_to_str =
372 *IntegerToString::dec(block + (MAX_BLOCK + 1), buf);
374 // copy the last block_digits characters into the start of end_buff.
375 // TODO: Replace with memcpy
376 for (int count = block_digits - 1; count >= 0; --count) {
377 end_buff[count] = int_to_str[count + 1 + (BLOCK_SIZE - block_digits)];
381 char low_digit;
382 if (block_digits > 0) {
383 low_digit = end_buff[block_digits - 1];
384 } else if (max_block_count > 0) {
385 low_digit = '9';
386 } else {
387 low_digit = block_buffer[buffered_digits - 1];
390 // Round up
391 if (round == RoundDirection::Up ||
392 (round == RoundDirection::Even && low_digit % 2 != 0)) {
393 bool has_carry = true;
394 // handle the low block that we're adding
395 for (int count = block_digits - 1; count >= 0 && has_carry; --count) {
396 if (end_buff[count] == '9') {
397 end_buff[count] = '0';
398 } else {
399 end_buff[count] += 1;
400 has_carry = false;
403 // handle the high block that's buffered
404 for (int count = buffered_digits - 1; count >= 0 && has_carry; --count) {
405 if (block_buffer[count] == '9') {
406 block_buffer[count] = '0';
407 } else {
408 block_buffer[count] += 1;
409 has_carry = false;
413 // has_carry should only be true here if every previous digit is 9, which
414 // implies that the number has never been written.
415 if (has_carry /* && !has_written */) {
416 // Since this is exponential notation, we don't write any more digits
417 // but we do increment the exponent.
418 ++exponent;
420 char buf[IntegerToString::dec_bufsize<intmax_t>()];
421 auto const int_to_str = exp_str(exponent, buf);
423 // TODO: also change this to calculate the width of the number more
424 // efficiently.
425 size_t exponent_width = int_to_str.size();
426 size_t number_digits =
427 buffered_digits + (max_block_count * BLOCK_SIZE) + block_digits;
429 // Here we have to recalculate the total number of digits since the
430 // exponent's width may have changed. We're only adding 1 to exponent
431 // width since exp_str appends the sign.
432 total_digits =
433 (has_decimal_point ? 1 : 0) + number_digits + 1 + exponent_width;
435 // Normally write_left_padding is called by flush_buffer but since we're
436 // rounding up all of the digits, the ones in the buffer are wrong and
437 // can't be flushed.
438 RET_IF_RESULT_NEGATIVE(
439 padding_writer.write_left_padding(writer, total_digits));
440 // Now we know we need to print a leading 1, the decimal point, and then
441 // zeroes after it.
442 RET_IF_RESULT_NEGATIVE(writer->write('1'));
443 // digits_before_decimal - 1 to account for the leading '1'
444 if (has_decimal_point) {
445 RET_IF_RESULT_NEGATIVE(writer->write(DECIMAL_POINT));
446 // This is just the length of the number, not including the decimal
447 // point, or exponent.
449 if (number_digits > 1) {
450 RET_IF_RESULT_NEGATIVE(writer->write('0', number_digits - 1));
453 RET_IF_RESULT_NEGATIVE(writer->write(exp_char));
454 RET_IF_RESULT_NEGATIVE(writer->write(int_to_str));
456 total_digits_written = total_digits;
457 return WRITE_OK;
460 // Either we intend to round down, or the rounding up is complete. Flush the
461 // buffers.
463 RET_IF_RESULT_NEGATIVE(flush_buffer());
465 // And then write the final block. It's written via the buffer so that if
466 // this is also the first block, the decimal point will be placed correctly.
468 // TODO: Replace with memcpy
469 for (size_t count = 0; count < block_digits; ++count) {
470 block_buffer[count] = end_buff[count];
472 buffered_digits = block_digits;
473 RET_IF_RESULT_NEGATIVE(flush_buffer());
475 char buf[IntegerToString::dec_bufsize<intmax_t>()];
476 auto const int_to_str = exp_str(exponent, buf);
478 RET_IF_RESULT_NEGATIVE(writer->write(exp_char));
479 RET_IF_RESULT_NEGATIVE(writer->write(int_to_str));
481 total_digits_written = total_digits;
483 return WRITE_OK;
486 int write_zeroes(uint32_t num_zeroes) {
487 RET_IF_RESULT_NEGATIVE(flush_buffer());
488 RET_IF_RESULT_NEGATIVE(writer->write('0', num_zeroes));
489 return 0;
492 int right_pad() {
493 return padding_writer.write_right_padding(writer, total_digits);
497 // This implementation is based on the Ryu Printf algorithm by Ulf Adams:
498 // Ulf Adams. 2019. Ryū revisited: printf floating point conversion.
499 // Proc. ACM Program. Lang. 3, OOPSLA, Article 169 (October 2019), 23 pages.
500 // https://doi.org/10.1145/3360595
501 template <typename T, cpp::enable_if_t<cpp::is_floating_point_v<T>, int> = 0>
502 LIBC_INLINE int convert_float_decimal_typed(Writer *writer,
503 const FormatSection &to_conv,
504 fputil::FPBits<T> float_bits) {
505 // signed because later we use -MANT_WIDTH
506 constexpr int32_t MANT_WIDTH = fputil::MantissaWidth<T>::VALUE;
507 bool is_negative = float_bits.get_sign();
508 int exponent = float_bits.get_exponent();
510 char sign_char = 0;
512 if (is_negative)
513 sign_char = '-';
514 else if ((to_conv.flags & FormatFlags::FORCE_SIGN) == FormatFlags::FORCE_SIGN)
515 sign_char = '+'; // FORCE_SIGN has precedence over SPACE_PREFIX
516 else if ((to_conv.flags & FormatFlags::SPACE_PREFIX) ==
517 FormatFlags::SPACE_PREFIX)
518 sign_char = ' ';
520 // If to_conv doesn't specify a precision, the precision defaults to 6.
521 const size_t precision = to_conv.precision < 0 ? 6 : to_conv.precision;
522 bool has_decimal_point =
523 (precision > 0) || ((to_conv.flags & FormatFlags::ALTERNATE_FORM) != 0);
525 // nonzero is false until a nonzero digit is found. It is used to determine if
526 // leading zeroes should be printed, since before the first digit they are
527 // ignored.
528 bool nonzero = false;
530 PaddingWriter padding_writer(to_conv, sign_char);
531 FloatWriter float_writer(writer, has_decimal_point, padding_writer);
532 FloatToString<T> float_converter(static_cast<T>(float_bits));
534 const uint32_t positive_blocks = float_converter.get_positive_blocks();
536 if (positive_blocks >= 0) {
537 // This loop iterates through the number a block at a time until it finds a
538 // block that is not zero or it hits the decimal point. This is because all
539 // zero blocks before the first nonzero digit or the decimal point are
540 // ignored (no leading zeroes, at least at this stage).
541 int32_t i = static_cast<int32_t>(positive_blocks) - 1;
542 for (; i >= 0; --i) {
543 BlockInt digits = float_converter.get_positive_block(i);
544 if (nonzero) {
545 RET_IF_RESULT_NEGATIVE(float_writer.write_middle_block(digits));
546 } else if (digits != 0) {
547 size_t blocks_before_decimal = i;
548 float_writer.init((blocks_before_decimal * BLOCK_SIZE) +
549 (has_decimal_point ? 1 : 0) + precision,
550 blocks_before_decimal * BLOCK_SIZE);
551 float_writer.write_first_block(digits);
553 nonzero = true;
558 // if we haven't yet found a valid digit, buffer a zero.
559 if (!nonzero) {
560 float_writer.init((has_decimal_point ? 1 : 0) + precision, 0);
561 float_writer.write_first_block(0);
564 if (exponent < MANT_WIDTH) {
565 const uint32_t blocks = (precision / BLOCK_SIZE) + 1;
566 uint32_t i = 0;
567 // if all the blocks we should write are zero
568 if (blocks <= float_converter.zero_blocks_after_point()) {
569 i = blocks; // just write zeroes up to precision
570 RET_IF_RESULT_NEGATIVE(float_writer.write_zeroes(precision));
571 } else if (i < float_converter.zero_blocks_after_point()) {
572 // else if there are some blocks that are zeroes
573 i = float_converter.zero_blocks_after_point();
574 // write those blocks as zeroes.
575 RET_IF_RESULT_NEGATIVE(float_writer.write_zeroes(9 * i));
577 // for each unwritten block
578 for (; i < blocks; ++i) {
579 if (float_converter.is_lowest_block(i)) {
580 const uint32_t fill = precision - 9 * i;
581 RET_IF_RESULT_NEGATIVE(float_writer.write_zeroes(fill));
582 break;
584 BlockInt digits = float_converter.get_negative_block(i);
585 if (i < blocks - 1) {
586 RET_IF_RESULT_NEGATIVE(float_writer.write_middle_block(digits));
587 } else {
589 const uint32_t maximum = precision - BLOCK_SIZE * i;
590 uint32_t last_digit = 0;
591 for (uint32_t k = 0; k < BLOCK_SIZE - maximum; ++k) {
592 last_digit = digits % 10;
593 digits /= 10;
595 RoundDirection round;
596 // Is m * 10^(additionalDigits + 1) / 2^(-exponent) integer?
597 const int32_t requiredTwos =
598 -(exponent - MANT_WIDTH) - static_cast<int32_t>(precision) - 1;
599 const bool trailingZeros =
600 requiredTwos <= 0 ||
601 (requiredTwos < 60 &&
602 multiple_of_power_of_2(float_bits.get_explicit_mantissa(),
603 static_cast<uint32_t>(requiredTwos)));
604 switch (fputil::quick_get_round()) {
605 case FE_TONEAREST:
606 // Round to nearest, if it's exactly halfway then round to even.
607 if (last_digit != 5) {
608 round = last_digit > 5 ? RoundDirection::Up : RoundDirection::Down;
609 } else {
610 round = trailingZeros ? RoundDirection::Even : RoundDirection::Up;
612 break;
613 case FE_DOWNWARD:
614 if (is_negative && (!trailingZeros || last_digit > 0)) {
615 round = RoundDirection::Up;
616 } else {
617 round = RoundDirection::Down;
619 break;
620 case FE_UPWARD:
621 if (!is_negative && (!trailingZeros || last_digit > 0)) {
622 round = RoundDirection::Up;
623 } else {
624 round = RoundDirection::Down;
626 round = is_negative ? RoundDirection::Down : RoundDirection::Up;
627 break;
628 case FE_TOWARDZERO:
629 round = RoundDirection::Down;
630 break;
632 RET_IF_RESULT_NEGATIVE(
633 float_writer.write_last_block_dec(digits, maximum, round));
634 break;
637 } else {
638 RET_IF_RESULT_NEGATIVE(float_writer.write_zeroes(precision));
640 RET_IF_RESULT_NEGATIVE(float_writer.right_pad());
641 return WRITE_OK;
644 template <typename T, cpp::enable_if_t<cpp::is_floating_point_v<T>, int> = 0>
645 LIBC_INLINE int convert_float_dec_exp_typed(Writer *writer,
646 const FormatSection &to_conv,
647 fputil::FPBits<T> float_bits) {
648 // signed because later we use -MANT_WIDTH
649 constexpr int32_t MANT_WIDTH = fputil::MantissaWidth<T>::VALUE;
650 bool is_negative = float_bits.get_sign();
651 int exponent = float_bits.get_exponent();
652 MantissaInt mantissa = float_bits.get_explicit_mantissa();
654 const char a = (to_conv.conv_name & 32) | 'A';
656 char sign_char = 0;
658 if (is_negative)
659 sign_char = '-';
660 else if ((to_conv.flags & FormatFlags::FORCE_SIGN) == FormatFlags::FORCE_SIGN)
661 sign_char = '+'; // FORCE_SIGN has precedence over SPACE_PREFIX
662 else if ((to_conv.flags & FormatFlags::SPACE_PREFIX) ==
663 FormatFlags::SPACE_PREFIX)
664 sign_char = ' ';
666 // If to_conv doesn't specify a precision, the precision defaults to 6.
667 const size_t precision = to_conv.precision < 0 ? 6 : to_conv.precision;
668 bool has_decimal_point =
669 (precision > 0) || ((to_conv.flags & FormatFlags::ALTERNATE_FORM) != 0);
671 PaddingWriter padding_writer(to_conv, sign_char);
672 FloatWriter float_writer(writer, has_decimal_point, padding_writer);
673 FloatToString<T> float_converter(static_cast<T>(float_bits));
675 size_t digits_written = 0;
676 int final_exponent = 0;
678 // Here we would subtract 1 to account for the fact that block 0 counts as a
679 // positive block, but the loop below accounts for this by starting with
680 // subtracting 1 from cur_block.
681 int cur_block;
683 if (exponent < 0) {
684 cur_block = -float_converter.zero_blocks_after_point();
685 } else {
686 cur_block = float_converter.get_positive_blocks();
689 BlockInt digits = 0;
691 // If the mantissa is 0, then the number is 0, meaning that looping until a
692 // non-zero block is found will loop forever. The first block is just 0.
693 if (mantissa != 0) {
694 // This loop finds the first block.
695 while (digits == 0) {
696 --cur_block;
697 digits = float_converter.get_block(cur_block);
699 } else {
700 cur_block = 0;
703 // TODO: Find a better way to calculate the number of digits in the
704 // initial block and exponent.
705 char buf[IntegerToString::dec_bufsize<intmax_t>()];
706 auto int_to_str = *IntegerToString::dec(digits, buf);
707 size_t block_width = int_to_str.size();
709 final_exponent = (cur_block * BLOCK_SIZE) + (block_width - 1);
710 int positive_exponent = final_exponent < 0 ? -final_exponent : final_exponent;
712 int_to_str = *IntegerToString::dec(positive_exponent, buf);
713 size_t exponent_width = int_to_str.size();
715 // Calculate the total number of digits in the number.
716 // 1 - the digit before the decimal point
717 // 1 - the decimal point (optional)
718 // precision - the number of digits after the decimal point
719 // 1 - the 'e' at the start of the exponent
720 // 1 - the sign at the start of the exponent
721 // max(2, exp width) - the digits of the exponent, min 2.
723 float_writer.init(1 + (has_decimal_point ? 1 : 0) + precision + 2 +
724 (exponent_width < 2 ? 2 : exponent_width),
727 // If this block is not the last block
728 if (block_width <= precision + 1) {
729 float_writer.write_first_block(digits, true);
730 digits_written += block_width;
731 --cur_block;
734 // For each middle block.
735 for (; digits_written + BLOCK_SIZE < precision + 1; --cur_block) {
736 digits = float_converter.get_block(cur_block);
738 RET_IF_RESULT_NEGATIVE(float_writer.write_middle_block(digits));
739 digits_written += BLOCK_SIZE;
742 digits = float_converter.get_block(cur_block);
744 size_t last_block_size = BLOCK_SIZE;
746 // if the last block is also the first block, then ignore leading zeroes.
747 if (digits_written == 0) {
748 // TODO: Find a better way to calculate the number of digits in a block.
749 char buf[IntegerToString::dec_bufsize<intmax_t>()];
750 auto int_to_str = *IntegerToString::dec(digits, buf);
751 last_block_size = int_to_str.size();
754 // This is the last block.
755 const uint32_t maximum = precision + 1 - digits_written;
756 uint32_t last_digit = 0;
757 for (uint32_t k = 0; k < last_block_size - maximum; ++k) {
758 last_digit = digits % 10;
759 digits /= 10;
762 // If the last block we read doesn't have the digit after the end of what
763 // we'll print, then we need to read the next block to get that digit.
764 if (maximum == last_block_size) {
765 BlockInt extra_block = float_converter.get_block(cur_block - 1);
766 last_digit = extra_block / ((MAX_BLOCK / 10) + 1);
769 RoundDirection round;
770 // Is m * 10^(additionalDigits + 1) / 2^(-exponent) integer?
771 const int32_t requiredTwos =
772 -(exponent - MANT_WIDTH) - static_cast<int32_t>(precision) - 1;
773 const bool trailingZeros =
774 requiredTwos <= 0 ||
775 (requiredTwos < 60 &&
776 multiple_of_power_of_2(float_bits.get_explicit_mantissa(),
777 static_cast<uint32_t>(requiredTwos)));
778 switch (fputil::quick_get_round()) {
779 case FE_TONEAREST:
780 // Round to nearest, if it's exactly halfway then round to even.
781 if (last_digit != 5) {
782 round = last_digit > 5 ? RoundDirection::Up : RoundDirection::Down;
783 } else {
784 round = trailingZeros ? RoundDirection::Even : RoundDirection::Up;
786 break;
787 case FE_DOWNWARD:
788 if (is_negative && (!trailingZeros || last_digit > 0)) {
789 round = RoundDirection::Up;
790 } else {
791 round = RoundDirection::Down;
793 break;
794 case FE_UPWARD:
795 if (!is_negative && (!trailingZeros || last_digit > 0)) {
796 round = RoundDirection::Up;
797 } else {
798 round = RoundDirection::Down;
800 round = is_negative ? RoundDirection::Down : RoundDirection::Up;
801 break;
802 case FE_TOWARDZERO:
803 round = RoundDirection::Down;
804 break;
806 RET_IF_RESULT_NEGATIVE(float_writer.write_last_block_exp(
807 digits, maximum, round, final_exponent, a + 'E' - 'A'));
809 RET_IF_RESULT_NEGATIVE(float_writer.right_pad());
810 return WRITE_OK;
813 template <typename T, cpp::enable_if_t<cpp::is_floating_point_v<T>, int> = 0>
814 LIBC_INLINE int convert_float_dec_auto_typed(Writer *writer,
815 const FormatSection &to_conv,
816 fputil::FPBits<T> float_bits) {
817 // signed because later we use -MANT_WIDTH
818 constexpr int32_t MANT_WIDTH = fputil::MantissaWidth<T>::VALUE;
819 bool is_negative = float_bits.get_sign();
820 int exponent = float_bits.get_exponent();
821 MantissaInt mantissa = float_bits.get_explicit_mantissa();
823 // From the standard: Let P (init_precision) equal the precision if nonzero, 6
824 // if the precision is omitted, or 1 if the precision is zero.
825 const size_t init_precision = to_conv.precision <= 0
826 ? (to_conv.precision == 0 ? 1 : 6)
827 : to_conv.precision;
829 // Then, if a conversion with style E would have an exponent of X
830 // (base_10_exp):
831 int base_10_exp = 0;
832 // If P > X >= -4 the conversion is with style F and precision P - (X + 1).
833 // Otherwise, the conversion is with style E and precision P - 1.
835 // For calculating the base 10 exponent, we need to process the number as if
836 // it has style E, so here we calculate the precision we'll use in that case.
837 const size_t exp_precision = init_precision - 1;
839 FloatToString<T> float_converter(static_cast<T>(float_bits));
841 // Here we would subtract 1 to account for the fact that block 0 counts as a
842 // positive block, but the loop below accounts for this by starting with
843 // subtracting 1 from cur_block.
844 int cur_block;
846 if (exponent < 0) {
847 cur_block = -float_converter.zero_blocks_after_point();
848 } else {
849 cur_block = float_converter.get_positive_blocks();
852 BlockInt digits = 0;
854 // If the mantissa is 0, then the number is 0, meaning that looping until a
855 // non-zero block is found will loop forever.
856 if (mantissa != 0) {
857 // This loop finds the first non-zero block.
858 while (digits == 0) {
859 --cur_block;
860 digits = float_converter.get_block(cur_block);
862 } else {
863 // In the case of 0.0, then it's always decimal format. If we don't have alt
864 // form then the trailing zeroes are trimmed to make "0", else the precision
865 // is 1 less than specified by the user.
866 FormatSection new_conv = to_conv;
867 if ((to_conv.flags & FormatFlags::ALTERNATE_FORM) != 0) {
868 // This is a style F conversion, making the precision P - 1 - X, but since
869 // this is for the number 0, X (the base 10 exponent) is always 0.
870 new_conv.precision = init_precision - 1;
871 } else {
872 new_conv.precision = 0;
874 return convert_float_decimal_typed<T>(writer, new_conv, float_bits);
877 size_t block_width = 0;
879 // TODO: Find a better way to calculate the number of digits in the
880 // initial block and exponent.
881 char buf[IntegerToString::dec_bufsize<intmax_t>()];
882 auto int_to_str = *IntegerToString::dec(digits, buf);
883 block_width = int_to_str.size();
886 size_t digits_checked = 0;
887 // TODO: look into unifying trailing_zeroes and trailing_nines. The number can
888 // end in a nine or a zero, but not both.
889 size_t trailing_zeroes = 0;
890 size_t trailing_nines = 0;
892 base_10_exp = (cur_block * BLOCK_SIZE) + (block_width - 1);
894 // If the first block is not also the last block
895 if (block_width <= exp_precision + 1) {
896 char buf[IntegerToString::dec_bufsize<intmax_t>()];
897 auto int_to_str = *IntegerToString::dec(digits, buf);
899 for (size_t i = 0; i < block_width; ++i) {
900 if (int_to_str[i] == '9') {
901 ++trailing_nines;
902 trailing_zeroes = 0;
903 } else if (int_to_str[i] == '0') {
904 ++trailing_zeroes;
905 trailing_nines = 0;
906 } else {
907 trailing_nines = 0;
908 trailing_zeroes = 0;
911 digits_checked += block_width;
912 --cur_block;
915 // Handle middle blocks
916 for (; digits_checked + BLOCK_SIZE < exp_precision + 1; --cur_block) {
917 digits = float_converter.get_block(cur_block);
918 digits_checked += BLOCK_SIZE;
919 if (digits == MAX_BLOCK) {
920 trailing_nines += 9;
921 trailing_zeroes = 0;
922 } else if (digits == 0) {
923 trailing_zeroes += 9;
924 trailing_nines = 0;
925 } else {
926 // The block is neither all nines nor all zeroes, so we need to figure out
927 // what it ends with.
928 trailing_nines = 0;
929 trailing_zeroes = 0;
930 BlockInt copy_of_digits = digits;
931 int cur_last_digit = copy_of_digits % 10;
932 // We only care if it ends in nines or zeroes.
933 while (copy_of_digits > 0 &&
934 (cur_last_digit == 9 || cur_last_digit == 0)) {
935 // If the next digit is not the same as the previous one, then there are
936 // no more contiguous trailing digits.
937 if ((copy_of_digits % 10) != cur_last_digit) {
938 break;
940 if (cur_last_digit == 9) {
941 ++trailing_nines;
942 } else if (cur_last_digit == 0) {
943 ++trailing_zeroes;
944 } else {
945 break;
947 copy_of_digits /= 10;
952 // Handle the last block
954 digits = float_converter.get_block(cur_block);
956 size_t last_block_size = BLOCK_SIZE;
958 char buf[IntegerToString::dec_bufsize<intmax_t>()];
959 auto int_to_str = *IntegerToString::dec(digits, buf);
961 int implicit_leading_zeroes = BLOCK_SIZE - int_to_str.size();
963 // if the last block is also the first block, then ignore leading zeroes.
964 if (digits_checked == 0) {
965 last_block_size = int_to_str.size();
966 implicit_leading_zeroes = 0;
967 } else {
968 // If the block is not the maximum size, that means it has leading
969 // zeroes, and zeroes are not nines.
970 if (implicit_leading_zeroes > 0) {
971 trailing_nines = 0;
974 // But leading zeroes are zeroes (that could be trailing).
975 trailing_zeroes += implicit_leading_zeroes;
978 int digits_requested = (exp_precision + 1) - digits_checked;
980 int digits_to_check = digits_requested - implicit_leading_zeroes;
981 if (digits_to_check < 0) {
982 digits_to_check = 0;
985 // Check the upper digits of this block.
986 for (int i = 0; i < digits_to_check; ++i) {
987 if (int_to_str[i] == '9') {
988 ++trailing_nines;
989 trailing_zeroes = 0;
990 } else if (int_to_str[i] == '0') {
991 ++trailing_zeroes;
992 trailing_nines = 0;
993 } else {
994 trailing_nines = 0;
995 trailing_zeroes = 0;
999 // Find the digit after the lowest digit that we'll actually print to
1000 // determine the rounding.
1001 const uint32_t maximum = exp_precision + 1 - digits_checked;
1002 uint32_t last_digit = 0;
1003 for (uint32_t k = 0; k < last_block_size - maximum; ++k) {
1004 last_digit = digits % 10;
1005 digits /= 10;
1008 // If the last block we read doesn't have the digit after the end of what
1009 // we'll print, then we need to read the next block to get that digit.
1010 if (maximum == last_block_size) {
1011 BlockInt extra_block = float_converter.get_block(cur_block - 1);
1012 last_digit = extra_block / ((MAX_BLOCK / 10) + 1);
1015 // TODO: unify this code across the three float conversions.
1016 RoundDirection round;
1017 // Is m * 10^(additionalDigits + 1) / 2^(-exponent) integer?
1018 const int32_t requiredTwos =
1019 -(exponent - MANT_WIDTH) - static_cast<int32_t>(exp_precision) - 1;
1020 // TODO: rename this variable to remove confusion with trailing_zeroes
1021 const bool trailingZeros =
1022 requiredTwos <= 0 ||
1023 (requiredTwos < 60 &&
1024 multiple_of_power_of_2(float_bits.get_explicit_mantissa(),
1025 static_cast<uint32_t>(requiredTwos)));
1026 switch (fputil::quick_get_round()) {
1027 case FE_TONEAREST:
1028 // Round to nearest, if it's exactly halfway then round to even.
1029 if (last_digit != 5) {
1030 round = last_digit > 5 ? RoundDirection::Up : RoundDirection::Down;
1031 } else {
1032 round = trailingZeros ? RoundDirection::Even : RoundDirection::Up;
1034 break;
1035 case FE_DOWNWARD:
1036 if (is_negative && (!trailingZeros || last_digit > 0)) {
1037 round = RoundDirection::Up;
1038 } else {
1039 round = RoundDirection::Down;
1041 break;
1042 case FE_UPWARD:
1043 if (!is_negative && (!trailingZeros || last_digit > 0)) {
1044 round = RoundDirection::Up;
1045 } else {
1046 round = RoundDirection::Down;
1048 round = is_negative ? RoundDirection::Down : RoundDirection::Up;
1049 break;
1050 case FE_TOWARDZERO:
1051 round = RoundDirection::Down;
1052 break;
1055 bool round_up;
1056 if (round == RoundDirection::Up) {
1057 round_up = true;
1058 } else if (round == RoundDirection::Down) {
1059 round_up = false;
1060 } else {
1061 // RoundDirection is even, so check the extra digit.
1062 uint32_t low_digit = digits % 10;
1063 round_up = (low_digit % 2) != 0;
1066 digits_checked += digits_requested;
1067 LIBC_ASSERT(digits_checked == init_precision);
1068 // At this point we should have checked all the digits requested by the
1069 // precision. We may increment this number 1 more if we round up all of the
1070 // digits, but at this point in the code digits_checked should always equal
1071 // init_precision.
1073 if (round_up) {
1074 // If all the digits that would be printed are nines, then rounding up means
1075 // that the base 10 exponent is one higher and all those nines turn to
1076 // zeroes (e.g. 999 -> 1000).
1077 if (trailing_nines == init_precision) {
1078 ++base_10_exp;
1079 trailing_zeroes = digits_checked;
1080 ++digits_checked;
1081 } else {
1082 // If there are trailing nines, they turn into trailing zeroes when
1083 // they're rounded up.
1084 if (trailing_nines > 0) {
1085 trailing_zeroes += trailing_nines;
1086 } else if (trailing_zeroes > 0) {
1087 // If there are trailing zeroes, then the last digit will be rounded up
1088 // to a 1 so they aren't trailing anymore.
1089 trailing_zeroes = 0;
1094 // if P > X >= -4, the conversion is with style f (or F) and precision equals
1095 // P - (X + 1).
1096 if (static_cast<int>(init_precision) > base_10_exp && base_10_exp >= -4) {
1097 FormatSection new_conv = to_conv;
1098 const size_t conv_precision = init_precision - (base_10_exp + 1);
1100 if ((to_conv.flags & FormatFlags::ALTERNATE_FORM) != 0) {
1101 new_conv.precision = conv_precision;
1102 } else {
1103 // If alt form isn't set, then we need to determine the number of trailing
1104 // zeroes and set the precision such that they are removed.
1105 int trimmed_precision =
1106 digits_checked - (base_10_exp + 1) - trailing_zeroes;
1107 if (trimmed_precision < 0) {
1108 trimmed_precision = 0;
1110 new_conv.precision =
1111 (static_cast<size_t>(trimmed_precision) > conv_precision)
1112 ? conv_precision
1113 : trimmed_precision;
1116 return convert_float_decimal_typed<T>(writer, new_conv, float_bits);
1117 } else {
1118 // otherwise, the conversion is with style e (or E) and precision equals
1119 // P - 1
1120 const size_t conv_precision = init_precision - 1;
1121 FormatSection new_conv = to_conv;
1122 if ((to_conv.flags & FormatFlags::ALTERNATE_FORM) != 0) {
1123 new_conv.precision = conv_precision;
1124 } else {
1125 // If alt form isn't set, then we need to determine the number of trailing
1126 // zeroes and set the precision such that they are removed.
1127 int trimmed_precision = digits_checked - 1 - trailing_zeroes;
1128 if (trimmed_precision < 0) {
1129 trimmed_precision = 0;
1131 new_conv.precision =
1132 (static_cast<size_t>(trimmed_precision) > conv_precision)
1133 ? conv_precision
1134 : trimmed_precision;
1136 return convert_float_dec_exp_typed<T>(writer, new_conv, float_bits);
1140 // TODO: unify the float converters to remove the duplicated checks for inf/nan.
1141 LIBC_INLINE int convert_float_decimal(Writer *writer,
1142 const FormatSection &to_conv) {
1143 if (to_conv.length_modifier == LengthModifier::L) {
1144 fputil::FPBits<long double>::UIntType float_raw = to_conv.conv_val_raw;
1145 fputil::FPBits<long double> float_bits(float_raw);
1146 if (!float_bits.is_inf_or_nan()) {
1147 return convert_float_decimal_typed<long double>(writer, to_conv,
1148 float_bits);
1150 } else {
1151 fputil::FPBits<double>::UIntType float_raw = to_conv.conv_val_raw;
1152 fputil::FPBits<double> float_bits(float_raw);
1153 if (!float_bits.is_inf_or_nan()) {
1154 return convert_float_decimal_typed<double>(writer, to_conv, float_bits);
1158 return convert_inf_nan(writer, to_conv);
1161 LIBC_INLINE int convert_float_dec_exp(Writer *writer,
1162 const FormatSection &to_conv) {
1163 if (to_conv.length_modifier == LengthModifier::L) {
1164 fputil::FPBits<long double>::UIntType float_raw = to_conv.conv_val_raw;
1165 fputil::FPBits<long double> float_bits(float_raw);
1166 if (!float_bits.is_inf_or_nan()) {
1167 return convert_float_dec_exp_typed<long double>(writer, to_conv,
1168 float_bits);
1170 } else {
1171 fputil::FPBits<double>::UIntType float_raw = to_conv.conv_val_raw;
1172 fputil::FPBits<double> float_bits(float_raw);
1173 if (!float_bits.is_inf_or_nan()) {
1174 return convert_float_dec_exp_typed<double>(writer, to_conv, float_bits);
1178 return convert_inf_nan(writer, to_conv);
1181 LIBC_INLINE int convert_float_dec_auto(Writer *writer,
1182 const FormatSection &to_conv) {
1183 if (to_conv.length_modifier == LengthModifier::L) {
1184 fputil::FPBits<long double>::UIntType float_raw = to_conv.conv_val_raw;
1185 fputil::FPBits<long double> float_bits(float_raw);
1186 if (!float_bits.is_inf_or_nan()) {
1187 return convert_float_dec_auto_typed<long double>(writer, to_conv,
1188 float_bits);
1190 } else {
1191 fputil::FPBits<double>::UIntType float_raw = to_conv.conv_val_raw;
1192 fputil::FPBits<double> float_bits(float_raw);
1193 if (!float_bits.is_inf_or_nan()) {
1194 return convert_float_dec_auto_typed<double>(writer, to_conv, float_bits);
1198 return convert_inf_nan(writer, to_conv);
1201 } // namespace printf_core
1202 } // namespace __llvm_libc
1204 #endif // LLVM_LIBC_SRC_STDIO_PRINTF_CORE_FLOAT_DEC_CONVERTER_H