Skip to content

Commit

Permalink
fix(printf): fix trailing field width in itoa conversion
Browse files Browse the repository at this point in the history
Fixes #21
  • Loading branch information
mpaland committed Aug 21, 2018
1 parent e6b5331 commit be30479
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
4 changes: 3 additions & 1 deletion printf.c
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ static inline unsigned int _atoi(const char** str)
// internal itoa format
static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t maxlen, char* buf, size_t len, bool negative, unsigned int base, unsigned int prec, unsigned int width, unsigned int flags)
{
const size_t start_idx = idx;

// pad leading zeros
while (!(flags & FLAGS_LEFT) && (len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = '0';
Expand Down Expand Up @@ -208,7 +210,7 @@ static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t ma

// append pad spaces up to given width
if (flags & FLAGS_LEFT) {
while (idx < width) {
while (idx - start_idx < width) {
out(' ', buffer, idx++, maxlen);
}
}
Expand Down
12 changes: 12 additions & 0 deletions test/test_suite.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,18 @@ TEST_CASE("width -20", "[]" ) {

test::sprintf(buffer, "%-20c", 'x');
REQUIRE(!strcmp(buffer, "x "));

test::sprintf(buffer, "|%5d| |%-2d| |%5d|", 9, 9, 9);
REQUIRE(!strcmp(buffer, "| 9| |9 | | 9|"));

test::sprintf(buffer, "|%5d| |%-2d| |%5d|", 10, 10, 10);
REQUIRE(!strcmp(buffer, "| 10| |10| | 10|"));

test::sprintf(buffer, "|%5d| |%-12d| |%5d|", 9, 9, 9);
REQUIRE(!strcmp(buffer, "| 9| |9 | | 9|"));

test::sprintf(buffer, "|%5d| |%-12d| |%5d|", 10, 10, 10);
REQUIRE(!strcmp(buffer, "| 10| |10 | | 10|"));
}


Expand Down

0 comments on commit be30479

Please sign in to comment.