Skip to content

Commit

Permalink
[libc] Fix printf %a padding issue
Browse files Browse the repository at this point in the history
The trailing zeroes were previously not counted when calculating the
padding, which caused a high-precision number to get too much padding.

Reviewed By: sivachandra

Differential Revision: https://reviews.llvm.org/D157534
  • Loading branch information
michaelrj-google committed Aug 15, 2023
1 parent 455d678 commit 89cdaa8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion libc/src/stdio/printf_core/float_hex_converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ LIBC_INLINE int convert_float_hex_exp(Writer *writer,
constexpr int EXP_SEPERATOR_LEN = 1;

padding = static_cast<int>(to_conv.min_width - (sign_char > 0 ? 1 : 0) -
PREFIX_LEN - mant_digits -
PREFIX_LEN - mant_digits - trailing_zeroes -
static_cast<int>(has_hexadecimal_point) -
EXP_SEPERATOR_LEN - (EXP_LEN - exp_cur));
if (padding < 0)
Expand Down
14 changes: 14 additions & 0 deletions libc/test/src/stdio/sprintf_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -865,6 +865,20 @@ TEST_F(LlvmLibcSPrintfTest, FloatHexExpConv) {

written = __llvm_libc::sprintf(buff, "%+-#12.3a % 012.3a", 0.1256, 1256.0);
ASSERT_STREQ_LEN(written, buff, "+0x1.014p-3 0x1.3a0p+10");

// These tests check that the padding is properly calculated based on the
// min_width field. Specifically, they check that the extra zeroes added by
// the high precision are accounted for correctly.
written = __llvm_libc::sprintf(buff, "%50.50a", 0x1.0p0);
ASSERT_STREQ_LEN(written, buff,
"0x1.00000000000000000000000000000000000000000000000000p+0");

// The difference with this test is that the formatted number is exactly 57
// characters, so padding to 58 adds a space.
written = __llvm_libc::sprintf(buff, "%58.50a", 0x1.0p0);
ASSERT_STREQ_LEN(
written, buff,
" 0x1.00000000000000000000000000000000000000000000000000p+0");
}

TEST_F(LlvmLibcSPrintfTest, FloatDecimalConv) {
Expand Down

0 comments on commit 89cdaa8

Please sign in to comment.