[libc][NFC] Move aligned access implementations to separate header
[llvm-project.git] / libc / src / stdio / printf_core / float_dec_converter.h
blob65fefdb113044819236a901013390e3140521b5e
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 template <typename T>
38 LIBC_INLINE constexpr cpp::enable_if_t<cpp::is_integral_v<T>, bool>
39 multiple_of_power_of_2(T value, uint32_t p) {
40 return (value & ((T(1) << p) - 1)) == 0;
43 constexpr size_t BLOCK_SIZE = 9;
44 constexpr uint32_t MAX_BLOCK = 999999999;
46 // constexpr size_t BLOCK_SIZE = 18;
47 // constexpr uint32_t MAX_BLOCK = 999999999999999999;
48 constexpr char DECIMAL_POINT = '.';
50 // This is used to represent which direction the number should be rounded.
51 enum class RoundDirection { Up, Down, Even };
53 class PaddingWriter {
54 bool left_justified = false;
55 bool leading_zeroes = false;
56 char sign_char = 0;
57 size_t min_width = 0;
59 public:
60 PaddingWriter() {}
61 PaddingWriter(const FormatSection &to_conv, char init_sign_char)
62 : left_justified((to_conv.flags & FormatFlags::LEFT_JUSTIFIED) > 0),
63 leading_zeroes((to_conv.flags & FormatFlags::LEADING_ZEROES) > 0),
64 sign_char(init_sign_char),
65 min_width(to_conv.min_width > 0 ? to_conv.min_width : 0) {}
67 int write_left_padding(Writer *writer, size_t total_digits) {
68 // The pattern is (spaces) (sign) (zeroes), but only one of spaces and
69 // zeroes can be written, and only if the padding amount is positive.
70 int padding_amount = min_width - total_digits - (sign_char > 0 ? 1 : 0);
71 if (left_justified || padding_amount < 0) {
72 if (sign_char > 0) {
73 RET_IF_RESULT_NEGATIVE(writer->write(sign_char));
75 return 0;
77 if (!leading_zeroes) {
78 RET_IF_RESULT_NEGATIVE(writer->write(' ', padding_amount));
80 if (sign_char > 0) {
81 RET_IF_RESULT_NEGATIVE(writer->write(sign_char));
83 if (leading_zeroes) {
84 RET_IF_RESULT_NEGATIVE(writer->write('0', padding_amount));
86 return 0;
89 int write_right_padding(Writer *writer, size_t total_digits) {
90 // If and only if the conversion is left justified, there may be trailing
91 // spaces.
92 int padding_amount = min_width - total_digits - (sign_char > 0 ? 1 : 0);
93 if (left_justified && padding_amount > 0) {
94 RET_IF_RESULT_NEGATIVE(writer->write(' ', padding_amount));
96 return 0;
101 We only need to round a given segment if all of the segments below it are
102 the max (or this is the last segment). This means that we don't have to
103 write those initially, we can just keep the most recent non-maximal
104 segment and a counter of the number of maximal segments. When we reach a
105 non-maximal segment, we write the stored segment as well as as many 9s as
106 are necessary. Alternately, if we reach the end and have to round up, then
107 we round the stored segment, and write zeroes following it. If this
108 crosses the decimal point, then we have to shift it one space to the
109 right.
110 This FloatWriter class does the buffering and counting, and writes to the
111 output when necessary.
113 class FloatWriter {
114 char block_buffer[BLOCK_SIZE]; // The buffer that holds a block.
115 size_t buffered_digits = 0; // The number of digits held in the buffer.
116 bool has_written = false; // True once any digits have been output.
117 size_t max_block_count = 0; // The # of blocks of all 9s currently buffered.
118 size_t total_digits = 0; // The number of digits that will be output.
119 size_t digits_before_decimal = 0; // The # of digits to write before the '.'
120 size_t total_digits_written = 0; // The # of digits that have been output.
121 bool has_decimal_point; // True if the number has a decimal point.
122 Writer *writer; // Writes to the final output.
123 PaddingWriter padding_writer; // Handles prefixes/padding, uses total_digits.
125 int flush_buffer() {
126 // Write the most recent buffered block, and mark has_written
127 if (!has_written) {
128 has_written = true;
129 RET_IF_RESULT_NEGATIVE(
130 padding_writer.write_left_padding(writer, total_digits));
133 // if the decimal point is the next character, or is in the range covered
134 // by the buffered block, write the appropriate digits and the decimal
135 // point.
136 if (total_digits_written < digits_before_decimal &&
137 total_digits_written + buffered_digits >= digits_before_decimal &&
138 has_decimal_point) {
139 size_t digits_to_write = digits_before_decimal - total_digits_written;
140 if (digits_to_write > 0) {
141 // Write the digits before the decimal point.
142 RET_IF_RESULT_NEGATIVE(writer->write({block_buffer, digits_to_write}));
144 RET_IF_RESULT_NEGATIVE(writer->write(DECIMAL_POINT));
145 if (buffered_digits - digits_to_write > 0) {
146 // Write the digits after the decimal point.
147 RET_IF_RESULT_NEGATIVE(
148 writer->write({block_buffer + digits_to_write,
149 (buffered_digits - digits_to_write)}));
151 // add 1 for the decimal point
152 total_digits_written += buffered_digits + 1;
153 // Mark the buffer as empty.
154 buffered_digits = 0;
157 // Clear the buffered digits.
158 if (buffered_digits > 0) {
159 RET_IF_RESULT_NEGATIVE(writer->write({block_buffer, buffered_digits}));
160 total_digits_written += buffered_digits;
161 buffered_digits = 0;
164 // if the decimal point is the next character, or is in the range covered
165 // by the max blocks, write the appropriate digits and the decimal point.
166 if (total_digits_written < digits_before_decimal &&
167 total_digits_written + BLOCK_SIZE * max_block_count >=
168 digits_before_decimal &&
169 has_decimal_point) {
170 size_t digits_to_write = digits_before_decimal - total_digits_written;
171 if (digits_to_write > 0) {
172 RET_IF_RESULT_NEGATIVE(writer->write('9', digits_to_write));
174 RET_IF_RESULT_NEGATIVE(writer->write(DECIMAL_POINT));
175 if ((BLOCK_SIZE * max_block_count) - digits_to_write > 0) {
176 RET_IF_RESULT_NEGATIVE(writer->write(
177 '9', (BLOCK_SIZE * max_block_count) - digits_to_write));
179 // add 1 for the decimal point
180 total_digits_written += BLOCK_SIZE * max_block_count + 1;
181 // clear the buffer of max blocks
182 max_block_count = 0;
185 // Clear the buffer of max blocks
186 if (max_block_count > 0) {
187 RET_IF_RESULT_NEGATIVE(writer->write('9', max_block_count * BLOCK_SIZE));
188 total_digits_written += max_block_count * BLOCK_SIZE;
189 max_block_count = 0;
191 return 0;
194 cpp::string_view exp_str(int exponent, cpp::span<char> exp_buffer) {
196 // -exponent will never overflow because all long double types we support
197 // have at most 15 bits of mantissa and the C standard defines an int as
198 // being at least 16 bits.
199 static_assert(fputil::FloatProperties<long double>::EXPONENT_WIDTH <
200 (sizeof(int) * 8));
202 int positive_exponent = exponent < 0 ? -exponent : exponent;
203 char exp_sign = exponent < 0 ? '-' : '+';
204 auto const int_to_str =
205 *IntegerToString::dec(positive_exponent, exp_buffer);
207 // IntegerToString writes the digits from right to left so there will be
208 // space to the left of int_to_str.
209 size_t digits_in_exp = int_to_str.size();
210 size_t index = exp_buffer.size() - digits_in_exp - 1;
212 // Ensure that at least two digits were written. IntegerToString always
213 // writes at least 1 digit (it writes "0" when the input number is 0).
214 if (digits_in_exp < 2) {
215 exp_buffer[index] = '0';
216 --index;
219 // Since the exp_buffer has to be sized to handle an intmax_t, it has space
220 // for a sign. In this case we're handling the sign on our own since we also
221 // want plus signs for positive numbers.
222 exp_buffer[index] = exp_sign;
224 return cpp::string_view(exp_buffer.data() + index,
225 exp_buffer.size() - index);
228 public:
229 FloatWriter(Writer *init_writer, bool init_has_decimal_point,
230 const PaddingWriter &init_padding_writer)
231 : has_decimal_point(init_has_decimal_point), writer(init_writer),
232 padding_writer(init_padding_writer) {}
234 void init(size_t init_total_digits, size_t init_digits_before_decimal) {
235 total_digits = init_total_digits;
236 digits_before_decimal = init_digits_before_decimal;
239 void write_first_block(BlockInt block, bool exp_format = false) {
240 char buf[IntegerToString::dec_bufsize<intmax_t>()];
241 auto const int_to_str = *IntegerToString::dec(block, buf);
242 size_t digits_buffered = int_to_str.size();
243 // Block Buffer is guaranteed to not overflow since block cannot have more
244 // than BLOCK_SIZE digits.
245 // TODO: Replace with memcpy
246 for (size_t count = 0; count < digits_buffered; ++count) {
247 block_buffer[count] = int_to_str[count];
249 buffered_digits = digits_buffered;
251 // In the exponent format (%e) we know how many digits will be written even
252 // before calculating any blocks, whereas the decimal format (%f) has to
253 // write all of the blocks that would come before the decimal place.
254 if (!exp_format) {
255 total_digits += digits_buffered;
256 digits_before_decimal += digits_buffered;
260 int write_middle_block(BlockInt block) {
261 if (block == MAX_BLOCK) { // Buffer max blocks in case of rounding
262 ++max_block_count;
263 } else { // If a non-max block has been found
264 RET_IF_RESULT_NEGATIVE(flush_buffer());
266 // Now buffer the current block. We add 1 + MAX_BLOCK to force the
267 // leading zeroes, and drop the leading one. This is probably inefficient,
268 // but it works. See https://xkcd.com/2021/
269 char buf[IntegerToString::dec_bufsize<intmax_t>()];
270 auto const int_to_str =
271 *IntegerToString::dec(block + (MAX_BLOCK + 1), buf);
272 // TODO: Replace with memcpy
273 for (size_t count = 0; count < BLOCK_SIZE; ++count) {
274 block_buffer[count] = int_to_str[count + 1];
277 buffered_digits = BLOCK_SIZE;
279 return 0;
282 int write_last_block_dec(BlockInt block, size_t block_digits,
283 RoundDirection round) {
284 char end_buff[BLOCK_SIZE];
286 char buf[IntegerToString::dec_bufsize<intmax_t>()];
287 auto const int_to_str = *IntegerToString::dec(block + (MAX_BLOCK + 1), buf);
289 // copy the last block_digits characters into the start of end_buff.
290 // TODO: Replace with memcpy
291 for (int count = block_digits - 1; count >= 0; --count) {
292 end_buff[count] = int_to_str[count + 1 + (BLOCK_SIZE - block_digits)];
295 char low_digit;
296 if (block_digits > 0) {
297 low_digit = end_buff[block_digits - 1];
298 } else if (max_block_count > 0) {
299 low_digit = '9';
300 } else {
301 low_digit = block_buffer[buffered_digits - 1];
304 // Round up
305 if (round == RoundDirection::Up ||
306 (round == RoundDirection::Even && low_digit % 2 != 0)) {
307 bool has_carry = true;
308 // handle the low block that we're adding
309 for (int count = block_digits - 1; count >= 0 && has_carry; --count) {
310 if (end_buff[count] == '9') {
311 end_buff[count] = '0';
312 } else {
313 end_buff[count] += 1;
314 has_carry = false;
317 // handle the high block that's buffered
318 for (int count = buffered_digits - 1; count >= 0 && has_carry; --count) {
319 if (block_buffer[count] == '9') {
320 block_buffer[count] = '0';
321 } else {
322 block_buffer[count] += 1;
323 has_carry = false;
327 // has_carry should only be true here if every previous digit is 9, which
328 // implies that the number has never been written.
329 if (has_carry /* && !has_written */) {
330 ++total_digits;
331 ++digits_before_decimal;
332 // Normally write_left_padding is called by flush_buffer but since we're
333 // rounding up all of the digits, the ones in the buffer are wrong and
334 // can't be flushed.
335 RET_IF_RESULT_NEGATIVE(
336 padding_writer.write_left_padding(writer, total_digits));
337 // Now we know we need to print a leading 1, zeroes up to the decimal
338 // point, the decimal point, and then finally digits after it.
339 RET_IF_RESULT_NEGATIVE(writer->write('1'));
340 // digits_before_decimal - 1 to account for the leading '1'
341 RET_IF_RESULT_NEGATIVE(writer->write('0', digits_before_decimal - 1));
342 if (has_decimal_point) {
343 RET_IF_RESULT_NEGATIVE(writer->write(DECIMAL_POINT));
344 // add one to digits_before_decimal to account for the decimal point
345 // itself.
346 if (total_digits > digits_before_decimal + 1) {
347 RET_IF_RESULT_NEGATIVE(
348 writer->write('0', total_digits - (digits_before_decimal + 1)));
351 total_digits_written = total_digits;
352 return 0;
355 // Either we intend to round down, or the rounding up is complete. Flush the
356 // buffers.
358 RET_IF_RESULT_NEGATIVE(flush_buffer());
360 // And then write the final block.
361 RET_IF_RESULT_NEGATIVE(writer->write({end_buff, block_digits}));
362 total_digits_written += block_digits;
363 return 0;
366 int write_last_block_exp(uint32_t block, size_t block_digits,
367 RoundDirection round, int exponent, char exp_char) {
368 char end_buff[BLOCK_SIZE];
371 char buf[IntegerToString::dec_bufsize<intmax_t>()];
372 auto const int_to_str =
373 *IntegerToString::dec(block + (MAX_BLOCK + 1), buf);
375 // copy the last block_digits characters into the start of end_buff.
376 // TODO: Replace with memcpy
377 for (int count = block_digits - 1; count >= 0; --count) {
378 end_buff[count] = int_to_str[count + 1 + (BLOCK_SIZE - block_digits)];
382 char low_digit;
383 if (block_digits > 0) {
384 low_digit = end_buff[block_digits - 1];
385 } else if (max_block_count > 0) {
386 low_digit = '9';
387 } else {
388 low_digit = block_buffer[buffered_digits - 1];
391 // Round up
392 if (round == RoundDirection::Up ||
393 (round == RoundDirection::Even && low_digit % 2 != 0)) {
394 bool has_carry = true;
395 // handle the low block that we're adding
396 for (int count = block_digits - 1; count >= 0 && has_carry; --count) {
397 if (end_buff[count] == '9') {
398 end_buff[count] = '0';
399 } else {
400 end_buff[count] += 1;
401 has_carry = false;
404 // handle the high block that's buffered
405 for (int count = buffered_digits - 1; count >= 0 && has_carry; --count) {
406 if (block_buffer[count] == '9') {
407 block_buffer[count] = '0';
408 } else {
409 block_buffer[count] += 1;
410 has_carry = false;
414 // has_carry should only be true here if every previous digit is 9, which
415 // implies that the number has never been written.
416 if (has_carry /* && !has_written */) {
417 // Since this is exponential notation, we don't write any more digits
418 // but we do increment the exponent.
419 ++exponent;
421 char buf[IntegerToString::dec_bufsize<intmax_t>()];
422 auto const int_to_str = exp_str(exponent, buf);
424 // TODO: also change this to calculate the width of the number more
425 // efficiently.
426 size_t exponent_width = int_to_str.size();
427 size_t number_digits =
428 buffered_digits + (max_block_count * BLOCK_SIZE) + block_digits;
430 // Here we have to recalculate the total number of digits since the
431 // exponent's width may have changed. We're only adding 1 to exponent
432 // width since exp_str appends the sign.
433 total_digits =
434 (has_decimal_point ? 1 : 0) + number_digits + 1 + exponent_width;
436 // Normally write_left_padding is called by flush_buffer but since we're
437 // rounding up all of the digits, the ones in the buffer are wrong and
438 // can't be flushed.
439 RET_IF_RESULT_NEGATIVE(
440 padding_writer.write_left_padding(writer, total_digits));
441 // Now we know we need to print a leading 1, the decimal point, and then
442 // zeroes after it.
443 RET_IF_RESULT_NEGATIVE(writer->write('1'));
444 // digits_before_decimal - 1 to account for the leading '1'
445 if (has_decimal_point) {
446 RET_IF_RESULT_NEGATIVE(writer->write(DECIMAL_POINT));
447 // This is just the length of the number, not including the decimal
448 // point, or exponent.
450 if (number_digits > 1) {
451 RET_IF_RESULT_NEGATIVE(writer->write('0', number_digits - 1));
454 RET_IF_RESULT_NEGATIVE(writer->write(exp_char));
455 RET_IF_RESULT_NEGATIVE(writer->write(int_to_str));
457 total_digits_written = total_digits;
458 return WRITE_OK;
461 // Either we intend to round down, or the rounding up is complete. Flush the
462 // buffers.
464 RET_IF_RESULT_NEGATIVE(flush_buffer());
466 // And then write the final block. It's written via the buffer so that if
467 // this is also the first block, the decimal point will be placed correctly.
469 // TODO: Replace with memcpy
470 for (size_t count = 0; count < block_digits; ++count) {
471 block_buffer[count] = end_buff[count];
473 buffered_digits = block_digits;
474 RET_IF_RESULT_NEGATIVE(flush_buffer());
476 char buf[IntegerToString::dec_bufsize<intmax_t>()];
477 auto const int_to_str = exp_str(exponent, buf);
479 RET_IF_RESULT_NEGATIVE(writer->write(exp_char));
480 RET_IF_RESULT_NEGATIVE(writer->write(int_to_str));
482 total_digits_written = total_digits;
484 return WRITE_OK;
487 int write_zeroes(uint32_t num_zeroes) {
488 RET_IF_RESULT_NEGATIVE(flush_buffer());
489 RET_IF_RESULT_NEGATIVE(writer->write('0', num_zeroes));
490 return 0;
493 int right_pad() {
494 return padding_writer.write_right_padding(writer, total_digits);
498 // This implementation is based on the Ryu Printf algorithm by Ulf Adams:
499 // Ulf Adams. 2019. Ryū revisited: printf floating point conversion.
500 // Proc. ACM Program. Lang. 3, OOPSLA, Article 169 (October 2019), 23 pages.
501 // https://doi.org/10.1145/3360595
502 template <typename T, cpp::enable_if_t<cpp::is_floating_point_v<T>, int> = 0>
503 LIBC_INLINE int convert_float_decimal_typed(Writer *writer,
504 const FormatSection &to_conv,
505 fputil::FPBits<T> float_bits) {
506 // signed because later we use -MANT_WIDTH
507 constexpr int32_t MANT_WIDTH = fputil::MantissaWidth<T>::VALUE;
508 bool is_negative = float_bits.get_sign();
509 int exponent = float_bits.get_exponent();
511 char sign_char = 0;
513 if (is_negative)
514 sign_char = '-';
515 else if ((to_conv.flags & FormatFlags::FORCE_SIGN) == FormatFlags::FORCE_SIGN)
516 sign_char = '+'; // FORCE_SIGN has precedence over SPACE_PREFIX
517 else if ((to_conv.flags & FormatFlags::SPACE_PREFIX) ==
518 FormatFlags::SPACE_PREFIX)
519 sign_char = ' ';
521 // If to_conv doesn't specify a precision, the precision defaults to 6.
522 const size_t precision = to_conv.precision < 0 ? 6 : to_conv.precision;
523 bool has_decimal_point =
524 (precision > 0) || ((to_conv.flags & FormatFlags::ALTERNATE_FORM) != 0);
526 // nonzero is false until a nonzero digit is found. It is used to determine if
527 // leading zeroes should be printed, since before the first digit they are
528 // ignored.
529 bool nonzero = false;
531 PaddingWriter padding_writer(to_conv, sign_char);
532 FloatWriter float_writer(writer, has_decimal_point, padding_writer);
533 FloatToString<T> float_converter(static_cast<T>(float_bits));
535 const uint32_t positive_blocks = float_converter.get_positive_blocks();
537 if (positive_blocks >= 0) {
538 // This loop iterates through the number a block at a time until it finds a
539 // block that is not zero or it hits the decimal point. This is because all
540 // zero blocks before the first nonzero digit or the decimal point are
541 // ignored (no leading zeroes, at least at this stage).
542 int32_t i = static_cast<int32_t>(positive_blocks) - 1;
543 for (; i >= 0; --i) {
544 BlockInt digits = float_converter.get_positive_block(i);
545 if (nonzero) {
546 RET_IF_RESULT_NEGATIVE(float_writer.write_middle_block(digits));
547 } else if (digits != 0) {
548 size_t blocks_before_decimal = i;
549 float_writer.init((blocks_before_decimal * BLOCK_SIZE) +
550 (has_decimal_point ? 1 : 0) + precision,
551 blocks_before_decimal * BLOCK_SIZE);
552 float_writer.write_first_block(digits);
554 nonzero = true;
559 // if we haven't yet found a valid digit, buffer a zero.
560 if (!nonzero) {
561 float_writer.init((has_decimal_point ? 1 : 0) + precision, 0);
562 float_writer.write_first_block(0);
565 if (exponent < MANT_WIDTH) {
566 const uint32_t blocks = (precision / BLOCK_SIZE) + 1;
567 uint32_t i = 0;
568 // if all the blocks we should write are zero
569 if (blocks <= float_converter.zero_blocks_after_point()) {
570 i = blocks; // just write zeroes up to precision
571 RET_IF_RESULT_NEGATIVE(float_writer.write_zeroes(precision));
572 } else if (i < float_converter.zero_blocks_after_point()) {
573 // else if there are some blocks that are zeroes
574 i = float_converter.zero_blocks_after_point();
575 // write those blocks as zeroes.
576 RET_IF_RESULT_NEGATIVE(float_writer.write_zeroes(9 * i));
578 // for each unwritten block
579 for (; i < blocks; ++i) {
580 if (float_converter.is_lowest_block(i)) {
581 const uint32_t fill = precision - 9 * i;
582 RET_IF_RESULT_NEGATIVE(float_writer.write_zeroes(fill));
583 break;
585 BlockInt digits = float_converter.get_negative_block(i);
586 if (i < blocks - 1) {
587 RET_IF_RESULT_NEGATIVE(float_writer.write_middle_block(digits));
588 } else {
590 const uint32_t maximum = precision - BLOCK_SIZE * i;
591 uint32_t last_digit = 0;
592 for (uint32_t k = 0; k < BLOCK_SIZE - maximum; ++k) {
593 last_digit = digits % 10;
594 digits /= 10;
596 RoundDirection round;
597 // Is m * 10^(additionalDigits + 1) / 2^(-exponent) integer?
598 const int32_t requiredTwos =
599 -(exponent - MANT_WIDTH) - static_cast<int32_t>(precision) - 1;
600 const bool trailingZeros =
601 requiredTwos <= 0 ||
602 (requiredTwos < 60 &&
603 multiple_of_power_of_2(float_bits.get_explicit_mantissa(),
604 static_cast<uint32_t>(requiredTwos)));
605 switch (fputil::quick_get_round()) {
606 case FE_TONEAREST:
607 // Round to nearest, if it's exactly halfway then round to even.
608 if (last_digit != 5) {
609 round = last_digit > 5 ? RoundDirection::Up : RoundDirection::Down;
610 } else {
611 round = trailingZeros ? RoundDirection::Even : RoundDirection::Up;
613 break;
614 case FE_DOWNWARD:
615 if (is_negative && (!trailingZeros || last_digit > 0)) {
616 round = RoundDirection::Up;
617 } else {
618 round = RoundDirection::Down;
620 break;
621 case FE_UPWARD:
622 if (!is_negative && (!trailingZeros || last_digit > 0)) {
623 round = RoundDirection::Up;
624 } else {
625 round = RoundDirection::Down;
627 round = is_negative ? RoundDirection::Down : RoundDirection::Up;
628 break;
629 case FE_TOWARDZERO:
630 round = RoundDirection::Down;
631 break;
633 RET_IF_RESULT_NEGATIVE(
634 float_writer.write_last_block_dec(digits, maximum, round));
635 break;
638 } else {
639 RET_IF_RESULT_NEGATIVE(float_writer.write_zeroes(precision));
641 RET_IF_RESULT_NEGATIVE(float_writer.right_pad());
642 return WRITE_OK;
645 template <typename T, cpp::enable_if_t<cpp::is_floating_point_v<T>, int> = 0>
646 LIBC_INLINE int convert_float_dec_exp_typed(Writer *writer,
647 const FormatSection &to_conv,
648 fputil::FPBits<T> float_bits) {
649 // signed because later we use -MANT_WIDTH
650 constexpr int32_t MANT_WIDTH = fputil::MantissaWidth<T>::VALUE;
651 bool is_negative = float_bits.get_sign();
652 int exponent = float_bits.get_exponent();
653 MantissaInt mantissa = float_bits.get_explicit_mantissa();
655 const char a = (to_conv.conv_name & 32) | 'A';
657 char sign_char = 0;
659 if (is_negative)
660 sign_char = '-';
661 else if ((to_conv.flags & FormatFlags::FORCE_SIGN) == FormatFlags::FORCE_SIGN)
662 sign_char = '+'; // FORCE_SIGN has precedence over SPACE_PREFIX
663 else if ((to_conv.flags & FormatFlags::SPACE_PREFIX) ==
664 FormatFlags::SPACE_PREFIX)
665 sign_char = ' ';
667 // If to_conv doesn't specify a precision, the precision defaults to 6.
668 const size_t precision = to_conv.precision < 0 ? 6 : to_conv.precision;
669 bool has_decimal_point =
670 (precision > 0) || ((to_conv.flags & FormatFlags::ALTERNATE_FORM) != 0);
672 PaddingWriter padding_writer(to_conv, sign_char);
673 FloatWriter float_writer(writer, has_decimal_point, padding_writer);
674 FloatToString<T> float_converter(static_cast<T>(float_bits));
676 size_t digits_written = 0;
677 int final_exponent = 0;
679 // Here we would subtract 1 to account for the fact that block 0 counts as a
680 // positive block, but the loop below accounts for this by starting with
681 // subtracting 1 from cur_block.
682 int cur_block;
684 if (exponent < 0) {
685 cur_block = -float_converter.zero_blocks_after_point();
686 } else {
687 cur_block = float_converter.get_positive_blocks();
690 BlockInt digits = 0;
692 // If the mantissa is 0, then the number is 0, meaning that looping until a
693 // non-zero block is found will loop forever. The first block is just 0.
694 if (mantissa != 0) {
695 // This loop finds the first block.
696 while (digits == 0) {
697 --cur_block;
698 digits = float_converter.get_block(cur_block);
700 } else {
701 cur_block = 0;
704 // TODO: Find a better way to calculate the number of digits in the
705 // initial block and exponent.
706 char buf[IntegerToString::dec_bufsize<intmax_t>()];
707 auto int_to_str = *IntegerToString::dec(digits, buf);
708 size_t block_width = int_to_str.size();
710 final_exponent = (cur_block * BLOCK_SIZE) + (block_width - 1);
711 int positive_exponent = final_exponent < 0 ? -final_exponent : final_exponent;
713 int_to_str = *IntegerToString::dec(positive_exponent, buf);
714 size_t exponent_width = int_to_str.size();
716 // Calculate the total number of digits in the number.
717 // 1 - the digit before the decimal point
718 // 1 - the decimal point (optional)
719 // precision - the number of digits after the decimal point
720 // 1 - the 'e' at the start of the exponent
721 // 1 - the sign at the start of the exponent
722 // max(2, exp width) - the digits of the exponent, min 2.
724 float_writer.init(1 + (has_decimal_point ? 1 : 0) + precision + 2 +
725 (exponent_width < 2 ? 2 : exponent_width),
728 // If this block is not the last block
729 if (block_width <= precision + 1) {
730 float_writer.write_first_block(digits, true);
731 digits_written += block_width;
732 --cur_block;
735 // For each middle block.
736 for (; digits_written + BLOCK_SIZE < precision + 1; --cur_block) {
737 digits = float_converter.get_block(cur_block);
739 RET_IF_RESULT_NEGATIVE(float_writer.write_middle_block(digits));
740 digits_written += BLOCK_SIZE;
743 digits = float_converter.get_block(cur_block);
745 size_t last_block_size = BLOCK_SIZE;
747 // if the last block is also the first block, then ignore leading zeroes.
748 if (digits_written == 0) {
749 // TODO: Find a better way to calculate the number of digits in a block.
750 char buf[IntegerToString::dec_bufsize<intmax_t>()];
751 auto int_to_str = *IntegerToString::dec(digits, buf);
752 last_block_size = int_to_str.size();
755 // This is the last block.
756 const uint32_t maximum = precision + 1 - digits_written;
757 uint32_t last_digit = 0;
758 for (uint32_t k = 0; k < last_block_size - maximum; ++k) {
759 last_digit = digits % 10;
760 digits /= 10;
763 // If the last block we read doesn't have the digit after the end of what
764 // we'll print, then we need to read the next block to get that digit.
765 if (maximum == last_block_size) {
766 BlockInt extra_block = float_converter.get_block(cur_block - 1);
767 last_digit = extra_block / ((MAX_BLOCK / 10) + 1);
770 RoundDirection round;
771 // Is m * 10^(additionalDigits + 1) / 2^(-exponent) integer?
772 const int32_t requiredTwos =
773 -(exponent - MANT_WIDTH) - static_cast<int32_t>(precision) - 1;
774 const bool trailingZeros =
775 requiredTwos <= 0 ||
776 (requiredTwos < 60 &&
777 multiple_of_power_of_2(float_bits.get_explicit_mantissa(),
778 static_cast<uint32_t>(requiredTwos)));
779 switch (fputil::quick_get_round()) {
780 case FE_TONEAREST:
781 // Round to nearest, if it's exactly halfway then round to even.
782 if (last_digit != 5) {
783 round = last_digit > 5 ? RoundDirection::Up : RoundDirection::Down;
784 } else {
785 round = trailingZeros ? RoundDirection::Even : RoundDirection::Up;
787 break;
788 case FE_DOWNWARD:
789 if (is_negative && (!trailingZeros || last_digit > 0)) {
790 round = RoundDirection::Up;
791 } else {
792 round = RoundDirection::Down;
794 break;
795 case FE_UPWARD:
796 if (!is_negative && (!trailingZeros || last_digit > 0)) {
797 round = RoundDirection::Up;
798 } else {
799 round = RoundDirection::Down;
801 round = is_negative ? RoundDirection::Down : RoundDirection::Up;
802 break;
803 case FE_TOWARDZERO:
804 round = RoundDirection::Down;
805 break;
807 RET_IF_RESULT_NEGATIVE(float_writer.write_last_block_exp(
808 digits, maximum, round, final_exponent, a + 'E' - 'A'));
810 RET_IF_RESULT_NEGATIVE(float_writer.right_pad());
811 return WRITE_OK;
814 template <typename T, cpp::enable_if_t<cpp::is_floating_point_v<T>, int> = 0>
815 LIBC_INLINE int convert_float_dec_auto_typed(Writer *writer,
816 const FormatSection &to_conv,
817 fputil::FPBits<T> float_bits) {
818 // signed because later we use -MANT_WIDTH
819 constexpr int32_t MANT_WIDTH = fputil::MantissaWidth<T>::VALUE;
820 bool is_negative = float_bits.get_sign();
821 int exponent = float_bits.get_exponent();
822 MantissaInt mantissa = float_bits.get_explicit_mantissa();
824 // From the standard: Let P (init_precision) equal the precision if nonzero, 6
825 // if the precision is omitted, or 1 if the precision is zero.
826 const size_t init_precision = to_conv.precision <= 0
827 ? (to_conv.precision == 0 ? 1 : 6)
828 : to_conv.precision;
830 // Then, if a conversion with style E would have an exponent of X
831 // (base_10_exp):
832 int base_10_exp = 0;
833 // If P > X >= -4 the conversion is with style F and precision P - (X + 1).
834 // Otherwise, the conversion is with style E and precision P - 1.
836 // For calculating the base 10 exponent, we need to process the number as if
837 // it has style E, so here we calculate the precision we'll use in that case.
838 const size_t exp_precision = init_precision - 1;
840 FloatToString<T> float_converter(static_cast<T>(float_bits));
842 // Here we would subtract 1 to account for the fact that block 0 counts as a
843 // positive block, but the loop below accounts for this by starting with
844 // subtracting 1 from cur_block.
845 int cur_block;
847 if (exponent < 0) {
848 cur_block = -float_converter.zero_blocks_after_point();
849 } else {
850 cur_block = float_converter.get_positive_blocks();
853 BlockInt digits = 0;
855 // If the mantissa is 0, then the number is 0, meaning that looping until a
856 // non-zero block is found will loop forever.
857 if (mantissa != 0) {
858 // This loop finds the first non-zero block.
859 while (digits == 0) {
860 --cur_block;
861 digits = float_converter.get_block(cur_block);
863 } else {
864 // In the case of 0.0, then it's always decimal format. If we don't have alt
865 // form then the trailing zeroes are trimmed to make "0", else the precision
866 // is 1 less than specified by the user.
867 FormatSection new_conv = to_conv;
868 if ((to_conv.flags & FormatFlags::ALTERNATE_FORM) != 0) {
869 // This is a style F conversion, making the precision P - 1 - X, but since
870 // this is for the number 0, X (the base 10 exponent) is always 0.
871 new_conv.precision = init_precision - 1;
872 } else {
873 new_conv.precision = 0;
875 return convert_float_decimal_typed<T>(writer, new_conv, float_bits);
878 size_t block_width = 0;
880 // TODO: Find a better way to calculate the number of digits in the
881 // initial block and exponent.
882 char buf[IntegerToString::dec_bufsize<intmax_t>()];
883 auto int_to_str = *IntegerToString::dec(digits, buf);
884 block_width = int_to_str.size();
887 size_t digits_checked = 0;
888 // TODO: look into unifying trailing_zeroes and trailing_nines. The number can
889 // end in a nine or a zero, but not both.
890 size_t trailing_zeroes = 0;
891 size_t trailing_nines = 0;
893 base_10_exp = (cur_block * BLOCK_SIZE) + (block_width - 1);
895 // If the first block is not also the last block
896 if (block_width <= exp_precision + 1) {
897 char buf[IntegerToString::dec_bufsize<intmax_t>()];
898 auto int_to_str = *IntegerToString::dec(digits, buf);
900 for (size_t i = 0; i < block_width; ++i) {
901 if (int_to_str[i] == '9') {
902 ++trailing_nines;
903 trailing_zeroes = 0;
904 } else if (int_to_str[i] == '0') {
905 ++trailing_zeroes;
906 trailing_nines = 0;
907 } else {
908 trailing_nines = 0;
909 trailing_zeroes = 0;
912 digits_checked += block_width;
913 --cur_block;
916 // Handle middle blocks
917 for (; digits_checked + BLOCK_SIZE < exp_precision + 1; --cur_block) {
918 digits = float_converter.get_block(cur_block);
919 digits_checked += BLOCK_SIZE;
920 if (digits == MAX_BLOCK) {
921 trailing_nines += 9;
922 trailing_zeroes = 0;
923 } else if (digits == 0) {
924 trailing_zeroes += 9;
925 trailing_nines = 0;
926 } else {
927 // The block is neither all nines nor all zeroes, so we need to figure out
928 // what it ends with.
929 trailing_nines = 0;
930 trailing_zeroes = 0;
931 BlockInt copy_of_digits = digits;
932 int cur_last_digit = copy_of_digits % 10;
933 // We only care if it ends in nines or zeroes.
934 while (copy_of_digits > 0 &&
935 (cur_last_digit == 9 || cur_last_digit == 0)) {
936 // If the next digit is not the same as the previous one, then there are
937 // no more contiguous trailing digits.
938 if ((copy_of_digits % 10) != cur_last_digit) {
939 break;
941 if (cur_last_digit == 9) {
942 ++trailing_nines;
943 } else if (cur_last_digit == 0) {
944 ++trailing_zeroes;
945 } else {
946 break;
948 copy_of_digits /= 10;
953 // Handle the last block
955 digits = float_converter.get_block(cur_block);
957 size_t last_block_size = BLOCK_SIZE;
959 char buf[IntegerToString::dec_bufsize<intmax_t>()];
960 auto int_to_str = *IntegerToString::dec(digits, buf);
962 int implicit_leading_zeroes = BLOCK_SIZE - int_to_str.size();
964 // if the last block is also the first block, then ignore leading zeroes.
965 if (digits_checked == 0) {
966 last_block_size = int_to_str.size();
967 implicit_leading_zeroes = 0;
968 } else {
969 // If the block is not the maximum size, that means it has leading
970 // zeroes, and zeroes are not nines.
971 if (implicit_leading_zeroes > 0) {
972 trailing_nines = 0;
975 // But leading zeroes are zeroes (that could be trailing).
976 trailing_zeroes += implicit_leading_zeroes;
979 int digits_requested = (exp_precision + 1) - digits_checked;
981 int digits_to_check = digits_requested - implicit_leading_zeroes;
982 if (digits_to_check < 0) {
983 digits_to_check = 0;
986 // Check the upper digits of this block.
987 for (int i = 0; i < digits_to_check; ++i) {
988 if (int_to_str[i] == '9') {
989 ++trailing_nines;
990 trailing_zeroes = 0;
991 } else if (int_to_str[i] == '0') {
992 ++trailing_zeroes;
993 trailing_nines = 0;
994 } else {
995 trailing_nines = 0;
996 trailing_zeroes = 0;
1000 // Find the digit after the lowest digit that we'll actually print to
1001 // determine the rounding.
1002 const uint32_t maximum = exp_precision + 1 - digits_checked;
1003 uint32_t last_digit = 0;
1004 for (uint32_t k = 0; k < last_block_size - maximum; ++k) {
1005 last_digit = digits % 10;
1006 digits /= 10;
1009 // If the last block we read doesn't have the digit after the end of what
1010 // we'll print, then we need to read the next block to get that digit.
1011 if (maximum == last_block_size) {
1012 BlockInt extra_block = float_converter.get_block(cur_block - 1);
1013 last_digit = extra_block / ((MAX_BLOCK / 10) + 1);
1016 // TODO: unify this code across the three float conversions.
1017 RoundDirection round;
1018 // Is m * 10^(additionalDigits + 1) / 2^(-exponent) integer?
1019 const int32_t requiredTwos =
1020 -(exponent - MANT_WIDTH) - static_cast<int32_t>(exp_precision) - 1;
1021 // TODO: rename this variable to remove confusion with trailing_zeroes
1022 const bool trailingZeros =
1023 requiredTwos <= 0 ||
1024 (requiredTwos < 60 &&
1025 multiple_of_power_of_2(float_bits.get_explicit_mantissa(),
1026 static_cast<uint32_t>(requiredTwos)));
1027 switch (fputil::quick_get_round()) {
1028 case FE_TONEAREST:
1029 // Round to nearest, if it's exactly halfway then round to even.
1030 if (last_digit != 5) {
1031 round = last_digit > 5 ? RoundDirection::Up : RoundDirection::Down;
1032 } else {
1033 round = trailingZeros ? RoundDirection::Even : RoundDirection::Up;
1035 break;
1036 case FE_DOWNWARD:
1037 if (is_negative && (!trailingZeros || last_digit > 0)) {
1038 round = RoundDirection::Up;
1039 } else {
1040 round = RoundDirection::Down;
1042 break;
1043 case FE_UPWARD:
1044 if (!is_negative && (!trailingZeros || last_digit > 0)) {
1045 round = RoundDirection::Up;
1046 } else {
1047 round = RoundDirection::Down;
1049 round = is_negative ? RoundDirection::Down : RoundDirection::Up;
1050 break;
1051 case FE_TOWARDZERO:
1052 round = RoundDirection::Down;
1053 break;
1056 bool round_up;
1057 if (round == RoundDirection::Up) {
1058 round_up = true;
1059 } else if (round == RoundDirection::Down) {
1060 round_up = false;
1061 } else {
1062 // RoundDirection is even, so check the extra digit.
1063 uint32_t low_digit = digits % 10;
1064 round_up = (low_digit % 2) != 0;
1067 digits_checked += digits_requested;
1068 LIBC_ASSERT(digits_checked == init_precision);
1069 // At this point we should have checked all the digits requested by the
1070 // precision. We may increment this number 1 more if we round up all of the
1071 // digits, but at this point in the code digits_checked should always equal
1072 // init_precision.
1074 if (round_up) {
1075 // If all the digits that would be printed are nines, then rounding up means
1076 // that the base 10 exponent is one higher and all those nines turn to
1077 // zeroes (e.g. 999 -> 1000).
1078 if (trailing_nines == init_precision) {
1079 ++base_10_exp;
1080 trailing_zeroes = digits_checked;
1081 ++digits_checked;
1082 } else {
1083 // If there are trailing nines, they turn into trailing zeroes when
1084 // they're rounded up.
1085 if (trailing_nines > 0) {
1086 trailing_zeroes += trailing_nines;
1087 } else if (trailing_zeroes > 0) {
1088 // If there are trailing zeroes, then the last digit will be rounded up
1089 // to a 1 so they aren't trailing anymore.
1090 trailing_zeroes = 0;
1095 // if P > X >= -4, the conversion is with style f (or F) and precision equals
1096 // P - (X + 1).
1097 if (static_cast<int>(init_precision) > base_10_exp && base_10_exp >= -4) {
1098 FormatSection new_conv = to_conv;
1099 const size_t conv_precision = init_precision - (base_10_exp + 1);
1101 if ((to_conv.flags & FormatFlags::ALTERNATE_FORM) != 0) {
1102 new_conv.precision = conv_precision;
1103 } else {
1104 // If alt form isn't set, then we need to determine the number of trailing
1105 // zeroes and set the precision such that they are removed.
1106 int trimmed_precision =
1107 digits_checked - (base_10_exp + 1) - trailing_zeroes;
1108 if (trimmed_precision < 0) {
1109 trimmed_precision = 0;
1111 new_conv.precision =
1112 (static_cast<size_t>(trimmed_precision) > conv_precision)
1113 ? conv_precision
1114 : trimmed_precision;
1117 return convert_float_decimal_typed<T>(writer, new_conv, float_bits);
1118 } else {
1119 // otherwise, the conversion is with style e (or E) and precision equals
1120 // P - 1
1121 const size_t conv_precision = init_precision - 1;
1122 FormatSection new_conv = to_conv;
1123 if ((to_conv.flags & FormatFlags::ALTERNATE_FORM) != 0) {
1124 new_conv.precision = conv_precision;
1125 } else {
1126 // If alt form isn't set, then we need to determine the number of trailing
1127 // zeroes and set the precision such that they are removed.
1128 int trimmed_precision = digits_checked - 1 - trailing_zeroes;
1129 if (trimmed_precision < 0) {
1130 trimmed_precision = 0;
1132 new_conv.precision =
1133 (static_cast<size_t>(trimmed_precision) > conv_precision)
1134 ? conv_precision
1135 : trimmed_precision;
1137 return convert_float_dec_exp_typed<T>(writer, new_conv, float_bits);
1141 // TODO: unify the float converters to remove the duplicated checks for inf/nan.
1142 LIBC_INLINE int convert_float_decimal(Writer *writer,
1143 const FormatSection &to_conv) {
1144 if (to_conv.length_modifier == LengthModifier::L) {
1145 fputil::FPBits<long double>::UIntType float_raw = to_conv.conv_val_raw;
1146 fputil::FPBits<long double> float_bits(float_raw);
1147 if (!float_bits.is_inf_or_nan()) {
1148 return convert_float_decimal_typed<long double>(writer, to_conv,
1149 float_bits);
1151 } else {
1152 fputil::FPBits<double>::UIntType float_raw =
1153 static_cast<fputil::FPBits<double>::UIntType>(to_conv.conv_val_raw);
1154 fputil::FPBits<double> float_bits(float_raw);
1155 if (!float_bits.is_inf_or_nan()) {
1156 return convert_float_decimal_typed<double>(writer, to_conv, float_bits);
1160 return convert_inf_nan(writer, to_conv);
1163 LIBC_INLINE int convert_float_dec_exp(Writer *writer,
1164 const FormatSection &to_conv) {
1165 if (to_conv.length_modifier == LengthModifier::L) {
1166 fputil::FPBits<long double>::UIntType float_raw = to_conv.conv_val_raw;
1167 fputil::FPBits<long double> float_bits(float_raw);
1168 if (!float_bits.is_inf_or_nan()) {
1169 return convert_float_dec_exp_typed<long double>(writer, to_conv,
1170 float_bits);
1172 } else {
1173 fputil::FPBits<double>::UIntType float_raw =
1174 static_cast<fputil::FPBits<double>::UIntType>(to_conv.conv_val_raw);
1175 fputil::FPBits<double> float_bits(float_raw);
1176 if (!float_bits.is_inf_or_nan()) {
1177 return convert_float_dec_exp_typed<double>(writer, to_conv, float_bits);
1181 return convert_inf_nan(writer, to_conv);
1184 LIBC_INLINE int convert_float_dec_auto(Writer *writer,
1185 const FormatSection &to_conv) {
1186 if (to_conv.length_modifier == LengthModifier::L) {
1187 fputil::FPBits<long double>::UIntType float_raw = to_conv.conv_val_raw;
1188 fputil::FPBits<long double> float_bits(float_raw);
1189 if (!float_bits.is_inf_or_nan()) {
1190 return convert_float_dec_auto_typed<long double>(writer, to_conv,
1191 float_bits);
1193 } else {
1194 fputil::FPBits<double>::UIntType float_raw =
1195 static_cast<fputil::FPBits<double>::UIntType>(to_conv.conv_val_raw);
1196 fputil::FPBits<double> float_bits(float_raw);
1197 if (!float_bits.is_inf_or_nan()) {
1198 return convert_float_dec_auto_typed<double>(writer, to_conv, float_bits);
1202 return convert_inf_nan(writer, to_conv);
1205 } // namespace printf_core
1206 } // namespace __llvm_libc
1208 #endif // LLVM_LIBC_SRC_STDIO_PRINTF_CORE_FLOAT_DEC_CONVERTER_H