Skip to content

Commit 7075d31

Browse files
committed
fix(printf): zero precision and zero value hash problem
Fixes #26
1 parent 6dae168 commit 7075d31

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

printf.c

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -163,9 +163,9 @@ static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t ma
163163

164164
// handle hash
165165
if (flags & FLAGS_HASH) {
166-
if (((len == prec) || (len == width)) && (len > 0U)) {
166+
if (len && ((len == prec) || (len == width))) {
167167
len--;
168-
if ((base == 16U) && (len > 0U)) {
168+
if (len && (base == 16U)) {
169169
len--;
170170
}
171171
}
@@ -181,7 +181,7 @@ static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t ma
181181
}
182182

183183
// handle sign
184-
if ((len == width) && (negative || (flags & FLAGS_PLUS) || (flags & FLAGS_SPACE))) {
184+
if (len && (len == width) && (negative || (flags & FLAGS_PLUS) || (flags & FLAGS_SPACE))) {
185185
len--;
186186
}
187187
if (len < PRINTF_NTOA_BUFFER_SIZE) {
@@ -225,6 +225,11 @@ static size_t _ntoa_long(out_fct_type out, char* buffer, size_t idx, size_t maxl
225225
char buf[PRINTF_NTOA_BUFFER_SIZE];
226226
size_t len = 0U;
227227

228+
// no hash for 0 values
229+
if (!value) {
230+
flags &= ~FLAGS_HASH;
231+
}
232+
228233
// write if precision != 0 and value is != 0
229234
if (!(flags & FLAGS_PRECISION) || value) {
230235
do {
@@ -245,6 +250,11 @@ static size_t _ntoa_long_long(out_fct_type out, char* buffer, size_t idx, size_t
245250
char buf[PRINTF_NTOA_BUFFER_SIZE];
246251
size_t len = 0U;
247252

253+
// no hash for 0 values
254+
if (!value) {
255+
flags &= ~FLAGS_HASH;
256+
}
257+
248258
// write if precision != 0 and value is != 0
249259
if (!(flags & FLAGS_PRECISION) || value) {
250260
do {

test/test_suite.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,9 @@ TEST_CASE("+ flag", "[]" ) {
247247

248248
test::sprintf(buffer, "%+c", 'x');
249249
REQUIRE(!strcmp(buffer, "x"));
250+
251+
test::sprintf(buffer, "%+.0d", 0);
252+
REQUIRE(!strcmp(buffer, "+"));
250253
}
251254

252255

@@ -344,6 +347,14 @@ TEST_CASE("- flag", "[]" ) {
344347
}
345348

346349

350+
TEST_CASE("# flag", "[]" ) {
351+
char buffer[100];
352+
353+
test::sprintf(buffer, "%#.0x", 0);
354+
REQUIRE(!strcmp(buffer, ""));
355+
}
356+
357+
347358
TEST_CASE("specifier", "[]" ) {
348359
char buffer[100];
349360

@@ -1232,6 +1243,9 @@ TEST_CASE("misc", "[]" ) {
12321243
test::sprintf(buffer, "%.3s", "foobar");
12331244
REQUIRE(!strcmp(buffer, "foo"));
12341245

1246+
test::sprintf(buffer, "% .0d", 0);
1247+
REQUIRE(!strcmp(buffer, " "));
1248+
12351249
test::sprintf(buffer, "%10.5d", 4);
12361250
REQUIRE(!strcmp(buffer, " 00004"));
12371251

0 commit comments

Comments
 (0)